﻿Imports System.Globalization

Partial Public Class SHIP_LD_PERFORMANCE_CONTROL_BULK
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Dim clsFc As New ClassFunction
    Dim numberFormat As New NumberFormatInfo()
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        numberFormat.NumberDecimalDigits = 3
        If Not IsPostBack Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "SHIP LOADING/UNLOADING PERFORMANCE CONTROL "

            txtPlanBerthFrom.Text = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
            txtPlanBerthTo.Text = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
            ViewState("TruckScale") = Nothing
            ViewState("countTruckType") = Nothing
            LoadBOoking()
            txtBookingVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtShipVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtProductSearch.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            Dim ds As DataTable = clsGet.Get_WharfAll("B")
            If (ds.Rows.Count > 0) Then
                With ddlWharfIn
                    .Items.Clear()
                    .ClearSelection()
                    .DataTextField = "Wharf"
                    .DataValueField = "BookingWharf"
                    .DataSource = ds
                    .DataBind()
                End With
                With ddlWharfOut
                    .Items.Clear()
                    .ClearSelection()
                    .DataTextField = "Wharf"
                    .DataValueField = "BookingWharf"
                    .DataSource = ds
                    .DataBind()
                End With
            End If
        End If
    End Sub

    Private Sub LoadBOoking()
        PanelBookingItem.Visible = True
        PanelShipLoading.Visible = False
        Dim ds As DataSet
        Dim DateFrom As String = ""
        Dim DateTo As String = ""
        If (txtDateSearch.Text.Trim <> "") And (txtDateToSearch.Text.Trim() <> "") Then
            DateFrom = txtDateSearch.Text.Split(" ")(2) & CDate(ClassFunctionGetData.CDateT(txtDateSearch.Text)).ToString("MMdd")
            DateTo = txtDateToSearch.Text.Split(" ")(2) & CDate(ClassFunctionGetData.CDateT(txtDateToSearch.Text)).ToString("MMdd")
        End If
        If (ddlStatusVPS.SelectedValue = "C") Then
            ds = clsGet.Get_Booking("", "", "", "'CV','CC','CM','CR','CA'", True, "B", txtShipVPS.Text, "", "", txtBookingVPS.Text, ddlDestinationSearch.SelectedValue, DateFrom, DateTo, txtProductSearch.Text)
        ElseIf (ddlStatusVPS.SelectedValue = "J") Then
            ds = clsGet.Get_Booking("", "", "", "'FN','OA'", True, "B", txtShipVPS.Text, "", "", txtBookingVPS.Text, ddlDestinationSearch.SelectedValue, DateFrom, DateTo, txtProductSearch.Text)
        ElseIf (ddlStatusVPS.SelectedValue = "A") Then
            ds = clsGet.Get_Booking("", "", "", "'MO'", True, "B", txtShipVPS.Text, "", "", txtBookingVPS.Text, ddlDestinationSearch.SelectedValue, DateFrom, DateTo, txtProductSearch.Text)
        Else
            ds = clsGet.Get_Booking("", "", "", "'MO'", True, "B", txtShipVPS.Text, "", "", txtBookingVPS.Text, ddlDestinationSearch.SelectedValue, DateFrom, DateTo, txtProductSearch.Text)


            Dim dsTemp As DataSet = ds.Copy
            Dim count As Integer = 0
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Dim dtStatus As DataTable = clsGet.Get_Load_Unload_Vessel(ds.Tables(0).Rows(i).Item("Booking_no"))
                If (ddlStatusVPS.SelectedValue = "L") Then
                    If (dtStatus.Rows.Count > 0) Then
                        If ((dtStatus.Rows(0).Item("Status") & "" = "C") Or (dtStatus.Rows(0).Item("Status") & "" = "A") Or (dtStatus.Rows(0).Item("Status") & "" = "S")) Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    End If
                ElseIf (ddlStatusVPS.SelectedValue = "U") Then
                    If (dtStatus.Rows.Count > 0) Then
                        If (Not (dtStatus.Rows(0).Item("Status") & "" = "S")) Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    Else
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                ElseIf (ddlStatusVPS.SelectedValue = "T") Then
                    dtStatus = clsGet.Get_Booking_LogSheet_Out(ds.Tables(0).Rows(i).Item("Booking_no"))
                    If (dtStatus.Rows.Count > 0) Then
                        If (dtStatus.Rows(0).Item("Status") & "" = "A") Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    Else
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Else 'Section
                    If (dtStatus.Rows.Count > 0) Then
                        If (Not (dtStatus.Rows(0).Item("Status") & "" = "C")) Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    Else
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                End If
            Next
            ds = dsTemp
            ds.AcceptChanges()

        End If

        If (txtPlanBerthFrom.Text <> "") And (txtPlanBerthTo.Text <> "") Then
            Dim c As Integer = 0
            Dim dtTemp As DataTable = ds.Tables(0).Copy
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Dim dtLogin As DataTable = clsGet.Get_BookingWharf(ds.Tables(0).Rows(i).Item("Booking_no"))
                Try
                    If (CDate(ClassFunctionGetData.CDateT(dtLogin.Rows(0).Item("Date_From"))) > CDate(ClassFunctionGetData.CDateT(txtPlanBerthFrom.Text))) Then
                        If (CDate(ClassFunctionGetData.CDateT(dtLogin.Rows(0).Item("Date_From"))) > CDate(ClassFunctionGetData.CDateT(txtPlanBerthTo.Text))) Then
                            dtTemp.Rows(i - c).Delete()
                            dtTemp.AcceptChanges()
                            c += 1
                        End If
                    ElseIf (CDate(ClassFunctionGetData.CDateT(dtLogin.Rows(0).Item("Date_To"))) < CDate(ClassFunctionGetData.CDateT(txtPlanBerthFrom.Text))) Then
                        dtTemp.Rows(i - c).Delete()
                        dtTemp.AcceptChanges()
                        c += 1
                    End If
                Catch ex As Exception
                    dtTemp.Rows(i - c).Delete()
                    dtTemp.AcceptChanges()
                    c += 1
                End Try
            Next
            ds.Tables.Clear()
            ds.Tables.Add(dtTemp.Copy)
            ds.AcceptChanges()
        End If

        If (ddlProductLD.SelectedValue <> "A") Then
            Dim dsTemp As DataSet = ds.Copy
            Dim count As Integer = 0
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Dim dt As DataTable = clsGet.Get_Booking_Product(ds.Tables(0).Rows(i).Item("Booking_no"))
                If (dt.Rows.Count > 0) Then
                    If (dt.Rows(0).Item("Product_Event") & "" <> ddlProductLD.SelectedValue) Then
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Else
                    dsTemp.Tables(0).Rows(i - count).Delete()
                    dsTemp.AcceptChanges()
                    count += 1
                End If
            Next
            ds = dsTemp
        End If
        ds.AcceptChanges()
        If (ds.Tables(0).Rows.Count > 0) Then
            ViewState("Operation") = ds
            gridItem.DataSource = ViewState("Operation")
            gridItem.DataBind()
            lbAlert.Text = ""
        Else
            gridItem.DataSource = Nothing
            gridItem.DataBind()
            lbAlert.Text = "ไม่พบรายการ Booking"
        End If
    End Sub

    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim CurrentIndex As Integer = gridItem.PageIndex
        Select Case e.CommandArgument.ToString().ToLower()
            Case "first"
                gridItem.PageIndex = 0
            Case "prev"
                If (gridItem.PageIndex <> 0) Then
                    gridItem.PageIndex = CurrentIndex - 1
                End If
            Case "next"
                If (gridItem.PageIndex <> gridItem.PageCount) Then
                    gridItem.PageIndex = CurrentIndex + 1
                End If
            Case "last"
                gridItem.PageIndex = gridItem.PageCount
        End Select
        gridItem.DataSource = ViewState("Operation")
        gridItem.DataBind()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim Page As GridViewRow = gridItem.BottomPagerRow
        Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
        gridItem.PageIndex = ddlPage.SelectedIndex
        gridItem.DataSource = ViewState("Operation")
        gridItem.DataBind()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Private Sub gridProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridProduct.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "L") Then
                lbDirection.Text = "LOADING"
            Else
                lbDirection.Text = "DISCHARGE"
            End If
            Dim lbTargetQuatity As Label = CType(e.Row.FindControl("lbTargetQuatity"), Label)
            Dim lbUnitType As Label = CType(e.Row.FindControl("lbUnitType"), Label)
            lbTargetQuatity.Text = gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Amount") & ""
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Group_no") & "" = "Bunker") Then
                lbUnitType.Text = "คัน"
            Else
                lbUnitType.Text = "MT"
            End If
        End If
    End Sub

    Private Sub gridItem_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridItem.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridItem.PageIndex <> 0) Then
            Index = Index Mod (gridItem.PageIndex * 10)
        End If
        If e.CommandName = "Edit" Then
            ViewState("Load") = ""
            LoadEdit(Index)
            Try
                If ViewState("Load") = "Not" Then
                    Timer1_Tick(sender, e)
                End If
            Catch ex As Exception

            End Try


        ElseIf e.CommandName = "Detail" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_IframeDetailPopup').src = '../FormPopup/Detail_VesselBerth_Popup.aspx';", True)
            Session("Booking_no_Detail") = gridItem.DataKeys(Index).Values("Booking_no")
            ModalPopupExtender5.Show()
        End If
    End Sub

    Private Sub LoadEdit(ByVal Index As Integer)
        ViewState("StandardTimeProductLast") = ""
        ViewState("StandardTimeProductLastDate") = ""
        ViewState("StopActual") = ""
        ViewState("EditBooking") = gridItem.DataKeys(Index).Values("Booking_no")
        ViewState("indexEdit") = Index
        lbBooking_no.Text = gridItem.DataKeys(Index).Values("Booking_no")
        lbVessel.Text = gridItem.DataKeys(Index).Values("Vehicle_Text")
        lbProduct.Text = gridItem.DataKeys(Index).Values("Product_name")
        If (gridItem.DataKeys(Index).Values("Status") & "" = "OA") Then
            btnSave.Visible = False
        Else
            btnSave.Visible = True
        End If
        Dim dt As DataTable = clsGet.Get_Booking_ProductOperationBulk(ViewState("EditBooking"))
        If (dt.Rows.Count > 1) Then
            For Each dr As DataRow In dt.Rows
                If (dr.Item("Product_Index") & "" = "") Then
                    ' ทำการ Popup หน้าจอระบุ Index สินค้า
                    Session("Booking_Index") = gridItem.DataKeys(Index).Values("Booking_no")
                    Session("Index_For_Save") = Index
                    'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " showIndex();", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_IframeIndex').src = '../FormPopup/ProductIndex_Bulk_Popup.aspx';", True)
                    ModalPopupExtender2.Show()
                    Exit Sub
                End If
            Next
        Else
            If (dt.Rows.Count > 0) Then
                If Not (InsertIndex(dt.Rows(0).Item("Booking_no"), dt.Rows(0).Item("Product_no"))) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดปัญหาในการจัดเรียงข้อมูลสินค้า กรุณาทำการลองใหม่อีกครั้ง!!');", True)
                    Exit Sub
                End If
            End If

        End If

        'Product_no,Group_no,Product_Event,Product_Amount,Product_name
        Try
            If (CDbl(gridItem.DataKeys(Index).Values("BunkerFO_Point")) > 0) Then
                Dim dr As DataRow = dt.NewRow()
                dr.Item("Product_no") = "Bunker FO"
                dr.Item("Group_no") = "Bunker"
                dr.Item("Product_Event") = "L"
                dr.Item("Product_Amount") = gridItem.DataKeys(Index).Values("BunkerFO_Point")
                dr.Item("Product_name") = "Bunker FO"
                ViewState("BunkerFO_Point") = gridItem.DataKeys(Index).Values("BunkerFO_Point")
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If
        Catch ex As Exception

        End Try
        Try
            If (CDbl(gridItem.DataKeys(Index).Values("BunkerDO_Point")) > 0) Then
                Dim dr As DataRow = dt.NewRow()
                dr.Item("Product_no") = "Bunker DO"
                dr.Item("Group_no") = "Bunker"
                dr.Item("Product_Event") = "L"
                dr.Item("Product_Amount") = gridItem.DataKeys(Index).Values("BunkerDO_Point")
                dr.Item("Product_name") = "Bunker DO"
                ViewState("BunkerDO_Point") = gridItem.DataKeys(Index).Values("BunkerDO_Point")
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If
        Catch ex As Exception

        End Try
        Dim Product_name As String = ""
        For Each dp As DataRow In dt.Rows
            If Product_name = "" Then
                Product_name = dp.Item("Product_name")
            Else
                Product_name &= "," & dp.Item("Product_name")
            End If
        Next
        lbProduct.Text = Product_name
        gridProduct.DataSource = dt
        gridProduct.DataBind()
        Dim str As String = clsGet.Get_Wharf_Shifting(ViewState("EditBooking"))
        If (str <> "") Then
            Try
                lbHShifting.Text = str.Split("-")(0) & " :"
                lbShifting.Text = str.Split("-")(1)
                rowShifting.Visible = True
            Catch ex As Exception
                rowShifting.Visible = False
            End Try
        Else
            rowShifting.Visible = False
        End If
        dt = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
        If (dt.Rows.Count = 1) Then
            If (dt.Rows(0).Item("Berthing_TimeTo") & "" <> "") Then
                lbarrived.Text = ConvertDate(dt.Rows(0).Item("Anchor_Date")) & " " & dt.Rows(0).Item("Anchor_Time")
                lbNOR.Text = ConvertDate(dt.Rows(0).Item("Anchor_Date")) & " " & dt.Rows(0).Item("Anchor_Time")
                lbPOB.Text = ConvertDate(dt.Rows(0).Item("POB_Date")) & " " & dt.Rows(0).Item("POB_Time")
                lbFirstling.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date")) & " " & dt.Rows(0).Item("Berthing_TimeFrom")
                Try
                    Dim TimeFrom As String = dt.Rows(0).Item("Berthing_TimeFrom").ToString.Replace(":", "")
                    Dim TimeTo As String = dt.Rows(0).Item("Berthing_TimeTo").ToString.Replace(":", "")
                    If (CDbl(TimeFrom) > CDbl(TimeTo)) Then
                        lbBerthedStandardDate.Text = ConvertDate(CDate(ClassFunctionGetData.CDateT(dt.Rows(0).Item("Berthing_Date"))).AddDays(1))
                        lbBerthedStandard.Text = dt.Rows(0).Item("Berthing_TimeTo")
                        lbBerthedDate.Text = ConvertDate(CDate(ClassFunctionGetData.CDateT(dt.Rows(0).Item("Berthing_Date"))).AddDays(1))
                        lbBerthed.Text = dt.Rows(0).Item("Berthing_TimeTo")
                        lbAccept.Text = ConvertDate(CDate(ClassFunctionGetData.CDateT(dt.Rows(0).Item("Berthing_Date"))).AddDays(1)) & " " & dt.Rows(0).Item("Berthing_TimeTo")
                    Else
                        lbBerthedStandardDate.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date"))
                        lbBerthedStandard.Text = dt.Rows(0).Item("Berthing_TimeTo")
                        lbBerthedDate.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date"))
                        lbBerthed.Text = dt.Rows(0).Item("Berthing_TimeTo")
                        lbAccept.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date")) & " " & dt.Rows(0).Item("Berthing_TimeTo")
                    End If
                Catch ex As Exception
                    lbBerthedStandardDate.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date"))
                    lbBerthedStandard.Text = dt.Rows(0).Item("Berthing_TimeTo")
                    lbBerthedDate.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date"))
                    lbBerthed.Text = dt.Rows(0).Item("Berthing_TimeTo")
                    lbAccept.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date")) & " " & dt.Rows(0).Item("Berthing_TimeTo")
                End Try

                lbPilotNo.Text = dt.Rows(0).Item("Pilot") & ""
                Try
                    txtNORTender.Text = CDate(ClassFunctionGetData.CDateT(dt.Rows(0).Item("Anchor_Date"))).ToString("dd/MM/yy")
                Catch ex As Exception
                    txtNORTender.Text = ""
                End Try
                txtNORTenderTime.Text = dt.Rows(0).Item("Anchor_Time") & ""
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เรือยังไม่ได้เข้าเทียบท่า!!');", True)
                LoadBOoking()
                ViewState("Load") = "Not"
                'Timer1_Tick(sender, e)
                Exit Sub
            End If
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เรือยังไม่ได้เข้าเทียบท่า!!');", True)
            LoadBOoking()
            ViewState("Load") = "Not"
            'Timer1_Tick(sender, e)
            Exit Sub
        End If

        dt = clsGet.Get_Load_Unload_Vessel(ViewState("EditBooking"))
        If (dt.Rows.Count > 0) Then
            txtThirdParty.Text = dt.Rows(0).Item("Third_Party") & ""
            txtDepartActualDate.Text = dt.Rows(0).Item("Depart_Actual_Date") & ""
            txtDepartAutualTime.Text = dt.Rows(0).Item("Depart_Actual_Time") & ""
            lbTugBefore.Text = dt.Rows(0).Item("Tug_Before") & ""
            lbTugAfter.Text = dt.Rows(0).Item("Tug_After") & ""
            ddlWharfIn.ClearSelection()
            If Not (ddlWharfIn.Items.FindByValue(dt.Rows(0).Item("Ship_Wharf") & "") Is Nothing) Then
                ddlWharfIn.SelectedValue = dt.Rows(0).Item("Ship_Wharf") & ""
            End If
            txtFenderIn.Text = dt.Rows(0).Item("Ship_Fender") & ""
            txtCompany.Text = dt.Rows(0).Item("Company") & ""
            txtEmployeeIn.Text = dt.Rows(0).Item("Company_Person") & ""
            txtFOR.Text = dt.Rows(0).Item("Draft_FOR") & ""
            txtAFT.Text = dt.Rows(0).Item("Draft_AFT") & ""
            txtInitialCompany.Text = dt.Rows(0).Item("Initial_Company") & ""
            txtInitialDateFrom.Text = dt.Rows(0).Item("Initial_DateFrom") & ""
            txtInitialDateTo.Text = dt.Rows(0).Item("Initial_DateTo") & ""
            txtInitialStart.Text = dt.Rows(0).Item("Initial_From") & ""
            txtInitialEnd.Text = dt.Rows(0).Item("Initial_To") & ""
            txtFOR_Out.Text = dt.Rows(0).Item("Draft_FOR_Out") & ""
            txtAFT_Out.Text = dt.Rows(0).Item("Draft_AFT_Out") & ""
            txtFinalCompany.Text = dt.Rows(0).Item("Final_Company") & ""
            txtFinalDateFrom.Text = dt.Rows(0).Item("Final_DateFrom") & ""
            txtFinalDateTo.Text = dt.Rows(0).Item("Final_DateTo") & ""
            txtFinalStart.Text = dt.Rows(0).Item("Final_From") & ""
            txtFinalEnd.Text = dt.Rows(0).Item("Final_To") & ""
            ddlWharfOut.ClearSelection()
            If Not (ddlWharfOut.Items.FindByValue(dt.Rows(0).Item("Ship_Wharf_Out") & "") Is Nothing) Then
                ddlWharfOut.SelectedValue = dt.Rows(0).Item("Ship_Wharf_Out") & ""
            End If
            txtFenderOut.Text = dt.Rows(0).Item("Ship_Fender_Out") & ""
            txtEmployeeOut.Text = dt.Rows(0).Item("Company_Person_Out") & ""
            txtNORTender.Text = dt.Rows(0).Item("NOR_Date") & ""
            txtNORTenderTime.Text = dt.Rows(0).Item("NOR_Time") & ""

            If (dt.Rows(0).Item("Status") & "" = "C") Then
                btnCheck.Visible = False
                btnSend.Visible = False
                If (Session("Role") = "00016") Then
                    btnApprove.Visible = True
                    btnReject.Visible = True
                    btnSave.Visible = True
                Else
                    btnReject.Visible = False
                    btnApprove.Visible = False
                    btnSave.Visible = False
                End If

            ElseIf (dt.Rows(0).Item("Status") & "" = "S") Then
                btnApprove.Visible = False
                btnSend.Visible = False
                If (Session("Role") = "00016") Or (Session("Role") = "00015") Then
                    btnCheck.Visible = True
                    btnReject.Visible = True
                Else
                    btnReject.Visible = False
                    btnSave.Visible = True
                    btnCheck.Visible = False
                End If

            ElseIf (dt.Rows(0).Item("Status") & "" = "A") Then
                btnCheck.Visible = False
                btnApprove.Visible = False
                btnSend.Visible = False
                btnReject.Visible = False
                If (Session("Role") = "00016") Then
                    btnSave.Visible = True
                Else
                    btnSave.Visible = False
                End If
            Else
                btnSave.Visible = True
                btnCheck.Visible = False
                btnApprove.Visible = False
                btnReject.Visible = False
                btnSend.Visible = True
            End If

            If Not ((Session("Role") = "00010") Or (Session("Role") = "00015") Or (Session("Role") = "00016")) Then
                btnSave.Visible = False
                btnApprove.Visible = False
                btnReject.Visible = False
                btnSend.Visible = False
                btnApprove.Visible = False
            End If

            dt = clsGet.Get_Action_Operation(ViewState("EditBooking"))
            Dim Status As String = ""
            For Each dx As DataRow In dt.Rows
                If (Status = "") Then
                    Status = dx.Item("A_Action") & " : " & dx.Item("A_By") & " " & dx.Item("A_Date") & " " & dx.Item("A_Time") & " " & dx.Item("A_Description")
                Else
                    Status &= "<br />" & dx.Item("A_Action") & " : " & dx.Item("A_By") & " " & dx.Item("A_Date") & " " & dx.Item("A_Time") & " " & dx.Item("A_Description")
                End If
            Next
            LiStatus.Text = Status
        Else
            LiStatus.Text = ""
            txtThirdParty.Text = String.Empty
            txtDepartActualDate.Text = String.Empty
            txtDepartAutualTime.Text = String.Empty
            lbTugBefore.Text = String.Empty
            lbTugAfter.Text = String.Empty
            ddlWharfIn.ClearSelection()
            txtFenderIn.Text = String.Empty
            txtCompany.Text = String.Empty
            txtEmployeeIn.Text = String.Empty
            txtFOR.Text = String.Empty
            txtAFT.Text = String.Empty
            txtInitialCompany.Text = String.Empty
            txtInitialDateFrom.Text = String.Empty
            txtInitialDateTo.Text = String.Empty
            txtInitialStart.Text = String.Empty
            txtInitialEnd.Text = String.Empty
            txtFOR_Out.Text = String.Empty
            txtAFT_Out.Text = String.Empty
            txtFinalCompany.Text = String.Empty
            txtFinalDateFrom.Text = String.Empty
            txtFinalDateTo.Text = String.Empty
            txtFinalStart.Text = String.Empty
            txtFinalEnd.Text = String.Empty
            ddlWharfOut.ClearSelection()
            txtFenderOut.Text = String.Empty
            txtEmployeeOut.Text = String.Empty

            btnSave.Visible = True
            btnCheck.Visible = False
            btnApprove.Visible = False
            btnReject.Visible = False
            btnSend.Visible = True
        End If
        dt = clsGet.Get_Load_Unload_Addition(ViewState("EditBooking"))
        If (dt.Rows.Count > 0) Then
            txtWater.Text = dt.Rows(0).Item("Water") & ""
            txtElectricity.Text = dt.Rows(0).Item("Electric") & ""
            txtHopper.Text = dt.Rows(0).Item("Hopper") & ""
            txtHopperFrom.Text = dt.Rows(0).Item("Hopper_From") & ""
            txtHopperTo.Text = dt.Rows(0).Item("Hopper_To") & ""
            txtHopperDateFrom.Text = dt.Rows(0).Item("Hopper_Date_From") & ""
            txtHopperDateTo.Text = dt.Rows(0).Item("Hopper_Date_To") & ""
        Else
            txtWater.Text = "0"
            txtElectricity.Text = "0"
            txtHopper.Text = "0"
            txtHopperFrom.Text = String.Empty
            txtHopperTo.Text = String.Empty
            txtHopperDateFrom.Text = String.Empty
            txtHopperDateTo.Text = String.Empty
        End If
        For i As Integer = 0 To gridProduct.Rows.Count - 1
            'Dim txtBL As TextBox = CType(gridProduct.Rows(i).FindControl("txtBL"), TextBox)
            'Dim txtDraftSurvey As TextBox = CType(gridProduct.Rows(i).FindControl("txtDraftSurvey"), TextBox)
            'Dim txtManifest As TextBox = CType(gridProduct.Rows(i).FindControl("txtManifest"), TextBox)
            'Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)

            Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
            Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)
            Dim lbStartActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartActualDate"), Label)
            Dim lbStartActual As Label = CType(gridProduct.Rows(i).FindControl("lbStartActual"), Label)
            'Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
            Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
            Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
            Dim lbStopActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopActualDate"), Label)
            Dim lbStopActual As Label = CType(gridProduct.Rows(i).FindControl("lbStopActual"), Label)

            Dim dtproduct As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), gridProduct.DataKeys(i).Values("BP_Code") & "")
            If (dtproduct.Rows.Count = 0) Then
                dtproduct = clsGet.Get_Load_Unload_Vessel_Product_Detail_Bunker(ViewState("EditBooking"), "")
            End If
            If (dtproduct.Rows.Count > 0) Then
                'txtBL.Text = dtproduct.Rows(0).Item("BU_Bill") & ""
                'txtDraftSurvey.Text = dtproduct.Rows(0).Item("BU_Draft") & ""
                'txtManifest.Text = dtproduct.Rows(0).Item("BU_Manifest") & ""
                'txtTruckScale.Text = dtproduct.Rows(0).Item("BU_Truck") & ""

                lbStartStandardTimeDate.Text = dtproduct.Rows(0).Item("LU_StartStandard_Date") & ""
                lbStartStandardTime.Text = dtproduct.Rows(0).Item("LU_StartStandard_Time") & ""
                lbStartActualDate.Text = dtproduct.Rows(0).Item("LU_StartActual_Date") & ""
                lbStartActual.Text = dtproduct.Rows(0).Item("LU_StartActual_Time") & ""
                'hdfgrid.Value = dtproduct.Rows(0).Item("BU_Product_Catalog") & ""
                lbStopStandardTimeDate.Text = dtproduct.Rows(0).Item("LU_StopStandard_Date") & ""
                lbStopStandardTime.Text = dtproduct.Rows(0).Item("LU_StopStandard_Time") & ""
                lbStopActualDate.Text = dtproduct.Rows(0).Item("LU_StopActual_Date") & ""
                lbStopActual.Text = dtproduct.Rows(0).Item("LU_StopActual_Time") & ""
            Else
                'txtBL.Text = String.Empty
                'txtDraftSurvey.Text = String.Empty
                'txtManifest.Text = String.Empty
                'txtTruckScale.Text = String.Empty

                lbStartStandardTimeDate.Text = String.Empty
                lbStartStandardTime.Text = String.Empty
                lbStartActualDate.Text = String.Empty
                lbStartActual.Text = String.Empty
                'hdfgrid.Value = "M"
                lbStopStandardTimeDate.Text = String.Empty
                lbStopStandardTime.Text = String.Empty
                lbStopActualDate.Text = String.Empty
                lbStopActual.Text = String.Empty
            End If

            clsGet.Get_Load_Unload_Product_Bulk(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), gridProduct.DataKeys(i).Values("BP_Code") & "")
            'Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
            'Dim CheckBoxList1 As CheckBoxList = CType(gridProduct.Rows(i).FindControl("CheckBoxList1"), CheckBoxList)
            'If (dtproduct.Rows.Count > 0) Then
            '    Dim _B As Double = 0.0
            '    Dim _T As Double = 0.0
            '    Dim _L As Double = 0.0
            '    Dim _P As Double = 0.0
            '    Dim _C As Double = 0.0
            '    Dim _R As Double = 0.0
            '    For Each dk As DataRow In dtproduct.Rows
            '        _B += CDbl(dk.Item("_B"))
            '        _T += CDbl(dk.Item("_T"))
            '        _L += CDbl(dk.Item("_L"))
            '        _P += CDbl(dk.Item("_P"))
            '        _C += CDbl(dk.Item("_C"))
            '        _R += CDbl(dk.Item("_R"))
            '    Next
            '    If (_B > 0) Then
            '        Grid.Columns(8).Visible = True
            '        Grid.Columns(9).Visible = True
            '        For Each li As ListItem In CheckBoxList1.Items
            '            If (li.Value = "B") Then
            '                li.Selected = True
            '            End If
            '        Next
            '    End If
            '    If (_T > 0) Then
            '        Grid.Columns(10).Visible = True
            '        Grid.Columns(11).Visible = True
            '        For Each li As ListItem In CheckBoxList1.Items
            '            If (li.Value = "T") Then
            '                li.Selected = True
            '            End If
            '        Next
            '    End If
            '    If (_L > 0) Then
            '        Grid.Columns(12).Visible = True
            '        Grid.Columns(13).Visible = True
            '        For Each li As ListItem In CheckBoxList1.Items
            '            If (li.Value = "L") Then
            '                li.Selected = True
            '            End If
            '        Next
            '    End If
            '    If (_P > 0) Then
            '        Grid.Columns(14).Visible = True
            '        Grid.Columns(15).Visible = True
            '        For Each li As ListItem In CheckBoxList1.Items
            '            If (li.Value = "P") Then
            '                li.Selected = True
            '            End If
            '        Next
            '    End If
            '    If (_C > 0) Then
            '        Grid.Columns(16).Visible = True
            '        Grid.Columns(17).Visible = True
            '        For Each li As ListItem In CheckBoxList1.Items
            '            If (li.Value = "C") Then
            '                li.Selected = True
            '            End If
            '        Next
            '    End If
            '    If (_R > 0) Then
            '        Grid.Columns(18).Visible = True
            '        Grid.Columns(19).Visible = True
            '        For Each li As ListItem In CheckBoxList1.Items
            '            If (li.Value = "R") Then
            '                li.Selected = True
            '            End If
            '        Next
            '    End If
            '    Grid.DataSource = dtproduct
            '    Grid.DataBind()
            '    Dim lbTruck6 As Label = CType(gridProduct.Rows(i).FindControl("lbTruck6"), Label)
            '    Dim lbTruck810 As Label = CType(gridProduct.Rows(i).FindControl("lbTruck810"), Label)
            '    Dim lbTrailer As Label = CType(gridProduct.Rows(i).FindControl("lbTrailer"), Label)
            '    Dim lbTrailer2 As Label = CType(gridProduct.Rows(i).FindControl("lbTrailer2"), Label)
            '    Dim lbTransferSum As Label = CType(gridProduct.Rows(i).FindControl("lbTransferSum"), Label)
            '    Try
            '        lbTruck6.Text = FormatNumber(ViewState("SumTruck6"), 0)
            '        lbTruck810.Text = FormatNumber(ViewState("SumTruck810"), 0)
            '        lbTrailer.Text = FormatNumber(ViewState("SumTrailer"), 0)
            '        lbTrailer2.Text = FormatNumber(ViewState("SumTrailer2"), 0)
            '        lbTransferSum.Text = FormatNumber(ViewState("SumTransfer"), 0)
            '    Catch ex As Exception
            '        lbTruck6.Text = ViewState("SumTruck6")
            '        lbTruck810.Text = ViewState("SumTruck810")
            '        lbTrailer.Text = ViewState("SumTrailer")
            '        lbTrailer2.Text = ViewState("SumTrailer2")
            '        lbTransferSum.Text = ViewState("SumTransfer")
            '    End Try
            '    ViewState("Start") = True
            'Else
            '    ViewState("Start") = False
            '    Grid.DataSource = Nothing
            '    Grid.DataBind()
            'End If
        Next



        Dim dtDelay As DataTable = clsGet.Get_Load_Unload_Delay(ViewState("EditBooking"))
        If (dtDelay.Rows.Count = 0) Then
            dtDelay = CreateTabelDelay()
        End If
        Session("Delay") = dtDelay
        gridDelay.DataSource = dtDelay
        gridDelay.DataBind()
        dtDelay = clsGet.Get_Load_Unload_Remark(ViewState("EditBooking"))
        If (dtDelay.Rows.Count = 0) Then
            dtDelay = CreateTabelRemark()
        End If
        Session("Remark") = dtDelay
        gridRemark.DataSource = dtDelay
        gridRemark.DataBind()
        'ยังไม่ทำการ BInd ค่ากรณีที่เคย save ไว้ ตอน BIne ที่Bind   TUg_Before , Tug_After ด้วย
        dt = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "I", "")
        Dim Tug_Name As String = ""
        For Each dr As DataRow In dt.Rows
            If (dr.Item("Tug_Name") & "" <> "") Then
                If (Tug_Name = "") Then
                    Tug_Name = dr.Item("Tug_Name")
                Else
                    Tug_Name &= "," & dr.Item("Tug_Name")
                End If
            End If
        Next
        lbTugBefore.Text = Tug_Name
        dt = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "O", "")
        Tug_Name = ""
        For Each dr As DataRow In dt.Rows
            If (dr.Item("Tug_Name") & "" <> "") Then
                If (Tug_Name = "") Then
                    Tug_Name = dr.Item("Tug_Name")
                Else
                    Tug_Name &= "," & dr.Item("Tug_Name")
                End If
            End If
        Next
        lbTugAfter.Text = Tug_Name

        PanelBookingItem.Visible = False
        PanelShipLoading.Visible = True
    End Sub

    Private Function InsertIndex(ByVal Booking_no As String, ByVal Product_no As String) As Boolean
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()

        tran = clsDB.BeginTran(conn)

        If (clsFc.UpdateBooking_Product_Index(Booking_no, Product_no, "1", "", "", "", "", "", "", "", "", "", "", conn, tran) < 1) Then
            condition = False
        End If
        If (condition) Then
            clsDB.CommitTran(tran)
            Return True
        Else
            clsDB.RollBackTran(tran)
            Return False
        End If
        Application.UnLock()
        conn.Dispose()
    End Function

    Private Function ConvertDate(ByVal value As String) As String
        Try
            Dim NewValue As String = CDate(ClassFunctionGetData.CDateT(value)).ToString("dd/MM/yy")
            Return NewValue
        Catch ex As Exception
            Return value
        End Try
    End Function


    Private Sub gridItem_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowCreated
        If e.Row.RowType = DataControlRowType.Header Then
            Dim Grid As GridView = CType(sender, GridView)
            e.Row.Cells.Clear()
            Dim GridRow As GridViewRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
            Dim GridRow1 As GridViewRow = New GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert)

            Dim table As TableCell = New TableCell()
            table.Text = "BOOKING NO."
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "VESSEL NAME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "STATUS"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "STATUS APPROVE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "LAY CAN/LAY DAY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REQUIRE DATE/TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "LAY TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)


            table = New TableCell()
            table.Text = "ATTACHMENT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "COMMODITY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "QUANTITY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "UNIT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "BUYER"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)


            table = New TableCell()
            table.Text = "SELLER"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "APPROVE BY MKT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.ColumnSpan = 5
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "APPROVE BY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.ColumnSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "TARIFF"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "AGENT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "WHARF"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN BERTH DATE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN BERTH TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN DEPART DATE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN DEPART TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "CONFIRM PLAN BERTH"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REMAIN LAYTIME(ESTIMATE)"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REMARK"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = ""
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            Grid.Controls(0).Controls.AddAt(0, GridRow1)

            table = New TableCell()
            table.Text = "PRODUCT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "CUSTOM"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "FINANCE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "DEMURRAGE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "TERM"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "PTMP"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "PTMI"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            Grid.Controls(0).Controls.AddAt(1, GridRow)
        End If
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If ViewState("Load") & "" <> "Not" Then
            LoadBOoking()
        Else
            ViewState("Load") = ""
        End If
        For i As Integer = 0 To gridItem.Rows.Count - 1
            Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(gridItem.DataKeys(i).Values("Booking_no"))
            If (dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "0") Then
                Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(gridItem.DataKeys(i).Values("Booking_no"))
                If Not (dtLogIn.Rows.Count = 0) Then
                    If Not (dtLogIn.Rows(0).Item("Berthing_Date") & "" = "") Or (dtLogIn.Rows(0).Item("Berthing_TimeTo") & "" = "") Then
                        If Not (dtLogIn.Rows(0).Item("POB_Date") & "" = "") Or (dtLogIn.Rows(0).Item("POB_Time") & "" = "") Then
                            Dim dtProduct As DataTable = clsGet.Get_Booking_Product(gridItem.DataKeys(i).Values("Booking_no"))
                            If Not (dtProduct.Rows.Count = 0) Then
                                If (dsBooking.Tables(0).Rows(0).Item("PORT") & "" = "L") Then
                                    Dim Product_no As String = ""
                                    Try
                                        Dim sort As Integer = 0
                                        For Each dr As DataRow In dtProduct.Rows
                                            If (CInt(dr.Item("Product_Index") & "") > sort) Then
                                                sort = CInt(dr.Item("Product_Index"))
                                                Product_no = dr.Item("Product_no")
                                            End If
                                        Next
                                    Catch ex As Exception

                                    End Try
                                    Dim dtLoad As DataTable = clsGet.Get_Load_Unload_Vessel(gridItem.DataKeys(i).Values("Booking_no"))
                                    Dim NOR As String = ""
                                    Dim NOR_Time As String = ""
                                    Dim POB As String = ""
                                    Dim POB_Time As String = ""
                                    If (dtLoad.Rows.Count > 0) Then
                                        If (dtLoad.Rows(0).Item("NOR_Date") & "" <> "") Then
                                            NOR = dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(3, 2)) & " 20" & dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(6, 2)
                                            NOR_Time = dtLoad.Rows(0).Item("NOR_Time") & ""
                                        Else
                                            NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                            NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                                        End If
                                    Else
                                        NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                        NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                                    End If
                                    If (dtLogIn.Rows(0).Item("POB_Date") & "" <> "") Then
                                        If (dtLogIn.Rows(0).Item("Up_Date") & "" <> "") Then
                                            If (CDate(ClassFunctionGetData.CDateT(dtLogIn.Rows(0).Item("POB_Date"))) < CDate(ClassFunctionGetData.CDateT(dtLogIn.Rows(0).Item("Up_Date")))) Then
                                                POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                            ElseIf (CDate(ClassFunctionGetData.CDateT(dtLogIn.Rows(0).Item("POB_Date"))) = CDate(ClassFunctionGetData.CDateT(dtLogIn.Rows(0).Item("Up_Date")))) Then
                                                If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                                    POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                    POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                                ElseIf (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) = CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                                    If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(1)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(1))) Then
                                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                                    Else
                                                        POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                        POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                                    End If
                                                Else
                                                    POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                    POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                                End If
                                            Else
                                                POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                            End If
                                        Else
                                            POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                            POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                        End If
                                    Else
                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                    End If

                                    dtLoad = clsGet.Get_Load_Unload_Product(gridItem.DataKeys(i).Values("Booking_no"), Product_no)
                                    Dim Dis_Date As String = ""
                                    Dim Dis_Time As String = ""
                                    For Each dl As DataRow In dtLoad.Rows
                                        Try
                                            If (Dis_Date = "") Then
                                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                            End If
                                            Dim _DD As String = Dis_Date.Substring(0, 2) & " " & GetNameMonth(Dis_Date.Substring(3, 2)) & " " & CInt("20" & Dis_Date.Substring(6, 2))
                                            Dim _D2 As String = dl.Item("LU_Disconnect_Date").Substring(0, 2) & " " & GetNameMonth(dl.Item("LU_Disconnect_Date").Substring(3, 2)) & " " & CInt("20" & dl.Item("LU_Disconnect_Date").Substring(6, 2))
                                            If (CDate(ClassFunctionGetData.CDateT(_DD)) < CDate(ClassFunctionGetData.CDateT(_D2))) Then
                                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                            ElseIf (CDate(ClassFunctionGetData.CDateT(_DD)) = CDate(ClassFunctionGetData.CDateT(_D2))) Then
                                                If (CInt(Dis_Time.Split(":")(0)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                                    Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                    Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                                ElseIf (CInt(Dis_Time.Split(":")(0)) = CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                                    Try
                                                        If (CInt(Dis_Time.Split(":")(1)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(1))) Then
                                                            Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                            Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                                        End If
                                                    Catch ex As Exception

                                                    End Try
                                                End If
                                            End If
                                        Catch ex As Exception

                                        End Try

                                    Next
                                    Dim Berthing_Date As String = dtLogIn.Rows(0).Item("Berthing_Date")
                                    Try
                                        Try
                                            If (CInt(dtLogIn.Rows(0).Item("Berthing_TimeTo").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Berthing_TimeFrom").ToString.Split(":")(0))) Then
                                                Berthing_Date = CDate(ClassFunctionGetData.CDateT(Berthing_Date)).AddDays(1).ToString("dd MMM", New CultureInfo("en-US")) & " " & Berthing_Date.Split(" ")(2)
                                            End If
                                        Catch ex As Exception

                                        End Try
                                    Catch ex As Exception

                                    End Try

                                    If (dtLoad.Rows.Count > 0) Then
                                        gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytime(Berthing_Date, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, Dis_Date & "", Dis_Time & "", NOR, NOR_Time)
                                    Else
                                        gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytime(Berthing_Date, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, "", "", NOR, NOR_Time)
                                    End If

                                Else
                                    Dim dtProductBulk As DataTable = clsGet.Get_Booking_Product(gridItem.DataKeys(i).Values("Booking_no"))
                                    If (dtProductBulk.Rows.Count > 0) Then
                                        Dim chkCoil As Boolean = False
                                        For Each dx As DataRow In dtProductBulk.Rows
                                            If (dx.Item("Group_no") & "" = "00007") Then
                                                chkCoil = True
                                                Exit For
                                            End If
                                        Next
                                        If (chkCoil) Then
                                            gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytimeBulk(dsBooking.Tables(0).Rows(0).Item("Lay_Time"), gridItem.DataKeys(i).Values("Booking_no"))
                                        End If
                                    End If
                                End If
                                If (gridItem.Rows(i).Cells(28).Text <> "") Then
                                    If (gridItem.Rows(i).Cells(28).Text.Substring(0, 1) = "-") Then
                                        gridItem.Rows(i).Cells(28).ForeColor = Drawing.Color.Red
                                    Else
                                        gridItem.Rows(i).Cells(28).ForeColor = Drawing.Color.Black
                                    End If
                                End If

                            End If
                        End If
                    End If
                End If
            End If
        Next
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub btnReLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReLoad.Click
        gridItem.DataSource = ViewState("Operation")
        gridItem.DataBind()
        LoadBOoking()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Private Sub gridItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim imgVPS As Image = CType(e.Row.FindControl("imgVPS"), Image)
            Dim imgMRI As Image = CType(e.Row.FindControl("imgMRI"), Image)
            Dim imgVPSComment As Image = CType(e.Row.FindControl("imgVPSComment"), Image)
            Dim imgMRIComment As Image = CType(e.Row.FindControl("imgMRIComment"), Image)
            Dim imgMKT As Image = CType(e.Row.FindControl("imgMKT"), Image)
            Dim imgProduct As Image = CType(e.Row.FindControl("imgProduct"), Image)
            Dim imgCustom As Image = CType(e.Row.FindControl("imgCustom"), Image)
            Dim imgFinance As Image = CType(e.Row.FindControl("imgFinance"), Image)
            Dim imgApprove As Image = CType(e.Row.FindControl("imgApprove"), Image)
            clsFc.GetImageStatus(imgVPS, imgMRI, imgMKT, gridItem.DataKeys(e.Row.RowIndex).Values("VPS_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("MRI_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("Marketing_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("Status"))
            clsFc.GetImageStatusMKT(imgProduct, imgCustom, imgFinance, gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Product"), gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Custom"), gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Finance"))

            If (gridItem.DataKeys(e.Row.RowIndex).Values("Payin") & "" = "0") Then
                Dim dt As DataTable = clsGet.Get_Booking_Gl_Account(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("MAgent_no"))
                If (dt.Rows.Count > 0) Then
                    imgMKT.ImageUrl = "~/Image/green.png"
                Else
                    imgMKT.ImageUrl = "~/Image/red.png"
                End If
            ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Marketing_approve") & "" = "") Then
                imgMKT.ImageUrl = "~/Image/red.png"
            Else
                imgMKT.ImageUrl = "~/Image/green.png"
            End If

            Dim dtap As DataTable = clsGet.Get_Load_Unload_Vessel(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            If (dtap.Rows.Count > 0) Then
                If (dtap.Rows(0).Item("Status") & "" = "C") Then
                    imgApprove.ImageUrl = "~/Image/blue.png"
                    imgApprove.ToolTip = "Waiting Approve by PTOBSEC"
                ElseIf (dtap.Rows(0).Item("Status") & "" = "A") Then
                    imgApprove.ImageUrl = "~/Image/green.png"
                    imgApprove.ToolTip = "Approve"
                ElseIf (dtap.Rows(0).Item("Status") & "" = "S") Then
                    imgApprove.ImageUrl = "~/Image/Yellow.png"
                    imgApprove.ToolTip = "Waiting Approve by PTOBDAY"
                ElseIf (dtap.Rows(0).Item("Status") & "" = "R") Then
                    imgApprove.ImageUrl = "~/Image/red.png"
                    imgApprove.ToolTip = "During Operation"
                Else
                    imgApprove.ImageUrl = "~/Image/red.png"
                    imgApprove.ToolTip = "During Operation"
                End If
            Else
                imgApprove.ImageUrl = "~/Image/red.png"
                imgApprove.ToolTip = "During Operation"
            End If

            If (gridItem.DataKeys(e.Row.RowIndex).Values("Remark_VPS") & "" <> "") Then
                imgVPSComment.Visible = True
            Else
                imgVPSComment.Visible = False
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Remark_MRI") & "" <> "") Then
                imgMRIComment.Visible = True
            Else
                imgMRIComment.Visible = False
            End If

            Dim imgConfrim As Image = CType(e.Row.FindControl("imgConfrim"), Image)
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Confirm_Time") & "" = "Y") Then
                imgConfrim.ImageUrl = "~/Image/4558.png"
            Else
                imgConfrim.ImageUrl = "~/Image/4557.gif"
            End If

            Dim Status As String = ""
            Dim Tooltip As String = ""
            clsGet.GetStatus_Working(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("PORT"), Status, Tooltip)
            e.Row.Cells(2).Text = Status
            e.Row.Cells(2).ToolTip = Tooltip

            If (gridItem.DataKeys(e.Row.RowIndex).Values("Date_From") & "" <> "") Then
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Date_From") & "" = gridItem.DataKeys(e.Row.RowIndex).Values("Date_To") & "") Then
                    e.Row.Cells(4).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Date_To")
                Else
                    e.Row.Cells(4).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Date_From").ToString.Substring(0, 2) & "-" & gridItem.DataKeys(e.Row.RowIndex).Values("Date_To")
                End If

                e.Row.Cells(5).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Booking_Date") & " : " & gridItem.DataKeys(e.Row.RowIndex).Values("Booking_Time")
                e.Row.Cells(6).Text = e.Row.Cells(6).Text & " hours"
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "F") Then
                        e.Row.Cells(18).Text = "FOB" 'รูปแบบการซื้อขาย
                    ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "C") Then
                        e.Row.Cells(18).Text = "CFR"
                    ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "I") Then
                        e.Row.Cells(18).Text = "CIF"
                    Else
                        e.Row.Cells(18).Text = "อื่นๆ" 'รูปแบบการซื้อขาย
                    End If
                Else
                    e.Row.Cells(18).Text = "" 'รูปแบบการซื้อขาย
                    e.Row.Cells(17).Text = ""
                End If
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage_Money") & "" = "B") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & "" = "") Then
                        e.Row.Cells(17).Text = "- BAHT"
                    Else
                        e.Row.Cells(17).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & " BAHT "
                    End If
                ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage_Money") & "" = "U") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & "" = "") Then
                        e.Row.Cells(17).Text = "- USD"
                    Else
                        e.Row.Cells(17).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & " USD "
                    End If
                End If
            End If

            Dim Product_Name As String = ""
            Dim Product_Amount As String = ""
            Dim Owner_name As String = ""
            Dim dtLog As DataTable
            dtLog = clsGet.Get_Booking_Product(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            For Each dr As DataRow In dtLog.Rows
                If (dr.Item("Product_name") & "" <> "") Then
                    If (Product_Name <> "") Then
                        Product_Name &= "<br />" & dr.Item("Product_name") & ""
                        Product_Amount &= "<br />" & dr.Item("Product_Amount") & ""
                        Owner_name &= "<br />" & dr.Item("Owner_Product_Name") & ""
                    Else
                        Product_Name = dr.Item("Product_name") & ""
                        Product_Amount = dr.Item("Product_Amount") & ""
                        Owner_name = dr.Item("Owner_Product_Name") & ""
                    End If
                End If
            Next
            If (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & "" <> "") And (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & "" <> "0") Then
                'BunkerFO 1 คัน,BunkerDO 1 คัน
                If Product_Name = "" Then
                    Product_Name = "BunkerFO"
                    Product_Amount = gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & " คัน"
                Else
                    Product_Name &= "<br />" & "BunkerFO"
                    Product_Amount &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & " คัน"
                End If
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & "" <> "") And (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & "" <> "0") Then
                If Product_Name = "" Then
                    Product_Name = "BunkerDO"
                    Product_Amount = gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & " คัน"
                Else
                    Product_Name &= "<br />" & "BunkerDO"
                    Product_Amount &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & " คัน"
                End If
            End If
            Dim File_Upload As String = ""
            If (gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload") & "" <> "") Then
                For i As Integer = 0 To gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",").Length - 1
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i) & "" <> "") Then
                        If File_Upload = "" Then
                            File_Upload = gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i)
                        Else
                            File_Upload &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i)
                        End If
                    End If
                Next
            End If
            e.Row.Cells(7).Text = File_Upload
            e.Row.Cells(8).Text = Product_Name
            e.Row.Cells(9).Text = Product_Amount
            Dim Unit() As String = (gridItem.DataKeys(e.Row.RowIndex).Values("Product_Unit") & "").ToString.Split(",")
            Dim Text As String = ""
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(10).Text = Text
            Text = ""
            Unit = (gridItem.DataKeys(e.Row.RowIndex).Values("BUYER") & "").ToString.Split(",")
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(11).Text = Text
            Text = ""
            Unit = (gridItem.DataKeys(e.Row.RowIndex).Values("SELLER") & "").ToString.Split(",")
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(12).Text = Text
            If (clsFc.GetStatusCancel(gridItem.DataKeys(e.Row.RowIndex).Values("Status"))) Then
                e.Row.BackColor = Drawing.Color.Red
            Else
                Dim Product_Event As String = clsGet.Get_ProductEvent(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
                If (Product_Event = "L") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                        e.Row.BackColor = Drawing.Color.FromName("#6698FF")
                    Else
                        e.Row.BackColor = Drawing.Color.FromName("#A0CFEC")
                    End If
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "B") Then
                        e.Row.Cells(11).Text = Owner_name
                    End If
                ElseIf (Product_Event = "D") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                        e.Row.BackColor = Drawing.Color.FromName("#347C17")
                    Else
                        e.Row.BackColor = Drawing.Color.FromName("#52D017")
                    End If
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "B") Then
                        e.Row.Cells(10).Text = Owner_name
                    End If
                Else
                    e.Row.BackColor = Drawing.Color.White
                End If
            End If
        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridItem.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridItem.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridItem.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridItem.PageCount.ToString()
            End If
        End If
    End Sub

   

    Private Sub gridItem_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridItem.RowEditing

    End Sub

    Private Function CreateTabelDelay() As DataTable
        Dim Dt As New DataTable
        Dt.Columns.Add("Delay_DateTime", GetType(String))
        Dt.Columns.Add("Cause_Delay", GetType(String))
        Dt.Columns.Add("Cause_Code", GetType(String))
        Dt.Columns.Add("Delay_Time", GetType(String))
        Dt.Columns.Add("Date_From", GetType(String))
        Dt.Columns.Add("Date_To", GetType(String))
        Dt.Columns.Add("Time_From", GetType(String))
        Dt.Columns.Add("Time_To", GetType(String))
        Dt.AcceptChanges()
        Return Dt
    End Function

    Private Function CreateTabelRemark() As DataTable
        Dim Dt As New DataTable
        Dt.Columns.Add("Remark", GetType(String))
        Dt.AcceptChanges()
        Return Dt
    End Function

    Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim CheckBoxList1 = DirectCast(sender, CheckBoxList)
        For i As Integer = 0 To gridProduct.Rows.Count - 1
            Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
            Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
            If (CheckBoxList1.ClientID.Replace("CheckBoxList1", "") = Grid.ClientID.Replace("gridTransfer", "")) Then
                For Each dr As ListItem In CheckBoxList1.Items
                    If (dr.Selected) Then
                        Select Case (dr.Value)
                            Case "M"
                                Grid.Columns(6).Visible = True
                                Grid.Columns(7).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("M", "")
                                hdfgrid.Value &= "M"
                            Case "P"
                                Grid.Columns(14).Visible = True
                                Grid.Columns(15).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("P", "")
                                hdfgrid.Value &= "P"
                            Case "B"
                                Grid.Columns(8).Visible = True
                                Grid.Columns(9).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("B", "")
                                hdfgrid.Value &= "B"
                            Case "T"
                                Grid.Columns(10).Visible = True
                                Grid.Columns(11).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("T", "")
                                hdfgrid.Value &= "T"
                            Case "C"
                                Grid.Columns(16).Visible = True
                                Grid.Columns(17).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("C", "")
                                hdfgrid.Value &= "C"
                            Case "R"
                                Grid.Columns(18).Visible = True
                                Grid.Columns(19).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("R", "")
                                hdfgrid.Value &= "R"
                            Case "L"
                                Grid.Columns(12).Visible = True
                                Grid.Columns(13).Visible = True
                                hdfgrid.Value = hdfgrid.Value.Replace("L", "")
                                hdfgrid.Value &= "L"
                        End Select
                    Else
                        Select Case (dr.Value)
                            Case "M"
                                Grid.Columns(6).Visible = False
                                Grid.Columns(7).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("M", "")
                            Case "P"
                                Grid.Columns(14).Visible = False
                                Grid.Columns(15).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("P", "")
                            Case "B"
                                Grid.Columns(8).Visible = False
                                Grid.Columns(9).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("B", "")
                            Case "T"
                                Grid.Columns(10).Visible = False
                                Grid.Columns(11).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("T", "")
                            Case "C"
                                Grid.Columns(16).Visible = False
                                Grid.Columns(17).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("C", "")
                            Case "R"
                                Grid.Columns(18).Visible = False
                                Grid.Columns(19).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("R", "")
                            Case "L"
                                Grid.Columns(12).Visible = False
                                Grid.Columns(13).Visible = False
                                hdfgrid.Value = hdfgrid.Value.Replace("L", "")
                        End Select
                    End If
                Next
            End If
            Dim s As String = hdfgrid.Value
        Next


    End Sub

    Protected Sub btnAddTransfer_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim btnAddTransfer = DirectCast(sender, Button)
        Dim gvr As GridViewRow = CType(btnAddTransfer.NamingContainer, GridViewRow)
        Session("gridProRow") = gvr.RowIndex.ToString()
        Session("gridTransferRowEdit") = Nothing
        ' Session("TruckScale" & gvr.RowIndex.ToString()) = Nothing
        For i As Integer = 0 To gridProduct.Rows.Count - 1
            Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
            If (btnAddTransfer.ClientID.Replace("btnAddTransfer", "") = hdfgrid.ClientID.Replace("hdfgrid", "")) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditTransfer').src = '../FormPopup/frm_Transfer_Product.aspx';", True)
                Session("hdfgrid") = hdfgrid.Value
                ModalPopupExtender1.Show()
                Exit Sub
            End If
        Next

    End Sub

    Private Sub btnTransferLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTransferLoad.Click
        Dim gridProRow As String
        Try
            gridProRow = Session("gridProRow")
        Catch ex As Exception
            gridProRow = 0
        End Try
        Dim gvrPro As GridViewRow = gridProduct.Rows(gridProRow)
        Dim gridTrans As GridView = CType(gvrPro.FindControl("gridTransfer"), GridView)
        gridTrans.DataSource = Session("TruckScale" & gridProRow)
        gridTrans.DataBind()
        ViewState("TruckScale") = Session("TruckScale" & gridProRow)



        Dim rowIndex As Integer = CInt(Session("gridTransferRowEdit"))
        Dim sessName As String = "truckTypeGroup" & gridProRow
        Dim dtTruckTypeCount As DataTable = CType(Session(sessName), DataTable)
        Dim reptTruck As Repeater = CType(gvrPro.FindControl("reptTruckCount"), Repeater)

        Dim dtEnum As IEnumerable(Of DataRow) = dtTruckTypeCount.AsEnumerable()
        Dim disT = From t In dtEnum Where t.Item("TruckType").ToString() <> "" _
               Group t By Key = t.Item("TruckType") Into Group Select TruckType = Key, TotalCount = Group.Sum(Function(p) p("cntType"))

        disT = From t In disT Where t.TotalCount > 0 Select t

        If (disT IsNot Nothing) Then
            reptTruck.DataSource = disT
            reptTruck.DataBind()
        End If

        'reptTruck.DataSource = dtTruckTypeCount
        'reptTruck.DataBind()
        ViewState("countTruckType") = dtTruckTypeCount
        'For i As Integer = 0 To gridProduct.Rows.Count - 1
        '    Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
        '    Dim ClientID As String = Session("hdfgrid").ToString().Split("$")(1)
        '    If (Grid.ClientID.Replace("gridTransfer", "") = ClientID) Then
        '        Session("hdfgrid") = Nothing
        '        Dim dt As DataTable = CreateDT()
        '        If (Session("IndexBulkProduct") Is Nothing) Then
        '            For m As Integer = 0 To Grid.Rows.Count - 1
        '                Dim drN As DataRow = dt.NewRow
        '                drN.Item("_Date") = Grid.DataKeys(m).Values("_Date")
        '                drN.Item("_Time") = Grid.DataKeys(m).Values("_Time")
        '                drN.Item("_Date2") = Grid.DataKeys(m).Values("_Date2")
        '                drN.Item("_Time2") = Grid.DataKeys(m).Values("_Time2")
        '                drN.Item("_DateSort") = Grid.DataKeys(m).Values("_DateSort")
        '                drN.Item("_STruck") = Grid.DataKeys(m).Values("_STruck")
        '                drN.Item("_Truck6") = Grid.DataKeys(m).Values("_Truck6")
        '                drN.Item("_Truck810") = Grid.DataKeys(m).Values("_Truck810")
        '                drN.Item("_Trailer") = Grid.DataKeys(m).Values("_Trailer")
        '                drN.Item("_Trailer2") = Grid.DataKeys(m).Values("_Trailer2")
        '                drN.Item("_M") = Grid.DataKeys(m).Values("_M")
        '                drN.Item("_P") = Grid.DataKeys(m).Values("_P")
        '                drN.Item("_B") = Grid.DataKeys(m).Values("_B")
        '                drN.Item("_T") = Grid.DataKeys(m).Values("_T")
        '                drN.Item("_C") = Grid.DataKeys(m).Values("_C")
        '                drN.Item("_R") = Grid.DataKeys(m).Values("_R")
        '                drN.Item("_L") = Grid.DataKeys(m).Values("_L")
        '                drN.Item("_Remark") = Grid.DataKeys(m).Values("_Remark")
        '                dt.Rows.Add(drN)
        '                dt.AcceptChanges()
        '            Next
        '            dt.Merge(Session("TransferValue"))
        '        Else
        '            For m As Integer = 0 To Grid.Rows.Count - 1
        '                If (m = CInt(Session("IndexBulkProduct"))) Then
        '                    Dim dtNew As DataTable = Session("TransferValue")
        '                    Dim drN As DataRow = dt.NewRow
        '                    drN.Item("_Date") = dtNew.Rows(0).Item("_Date")
        '                    drN.Item("_Time") = dtNew.Rows(0).Item("_Time")
        '                    drN.Item("_Date2") = dtNew.Rows(0).Item("_Date2")
        '                    drN.Item("_Time2") = dtNew.Rows(0).Item("_Time2")
        '                    drN.Item("_DateSort") = dtNew.Rows(0).Item("_DateSort")
        '                    drN.Item("_STruck") = dtNew.Rows(0).Item("_STruck")
        '                    drN.Item("_Truck6") = dtNew.Rows(0).Item("_Truck6")
        '                    drN.Item("_Truck810") = dtNew.Rows(0).Item("_Truck810")
        '                    drN.Item("_Trailer") = dtNew.Rows(0).Item("_Trailer")
        '                    drN.Item("_Trailer2") = dtNew.Rows(0).Item("_Trailer2")
        '                    drN.Item("_M") = dtNew.Rows(0).Item("_M")
        '                    drN.Item("_P") = dtNew.Rows(0).Item("_P")
        '                    drN.Item("_B") = dtNew.Rows(0).Item("_B")
        '                    drN.Item("_T") = dtNew.Rows(0).Item("_T")
        '                    drN.Item("_C") = dtNew.Rows(0).Item("_C")
        '                    drN.Item("_R") = dtNew.Rows(0).Item("_R")
        '                    drN.Item("_L") = dtNew.Rows(0).Item("_L")
        '                    drN.Item("_Remark") = dtNew.Rows(0).Item("_Remark")
        '                    dt.Rows.Add(drN)
        '                    dt.AcceptChanges()
        '                Else
        '                    Dim drN As DataRow = dt.NewRow
        '                    drN.Item("_Date") = Grid.DataKeys(m).Values("_Date")
        '                    drN.Item("_Time") = Grid.DataKeys(m).Values("_Time")
        '                    drN.Item("_Date2") = Grid.DataKeys(m).Values("_Date2")
        '                    drN.Item("_Time2") = Grid.DataKeys(m).Values("_Time2")
        '                    drN.Item("_DateSort") = Grid.DataKeys(m).Values("_DateSort")
        '                    drN.Item("_STruck") = Grid.DataKeys(m).Values("_STruck")
        '                    drN.Item("_Truck6") = Grid.DataKeys(m).Values("_Truck6")
        '                    drN.Item("_Truck810") = Grid.DataKeys(m).Values("_Truck810")
        '                    drN.Item("_Trailer") = Grid.DataKeys(m).Values("_Trailer")
        '                    drN.Item("_Trailer2") = Grid.DataKeys(m).Values("_Trailer2")
        '                    drN.Item("_M") = Grid.DataKeys(m).Values("_M")
        '                    drN.Item("_P") = Grid.DataKeys(m).Values("_P")
        '                    drN.Item("_B") = Grid.DataKeys(m).Values("_B")
        '                    drN.Item("_T") = Grid.DataKeys(m).Values("_T")
        '                    drN.Item("_C") = Grid.DataKeys(m).Values("_C")
        '                    drN.Item("_R") = Grid.DataKeys(m).Values("_R")
        '                    drN.Item("_L") = Grid.DataKeys(m).Values("_L")
        '                    drN.Item("_Remark") = Grid.DataKeys(m).Values("_Remark")
        '                    dt.Rows.Add(drN)
        '                    dt.AcceptChanges()
        '                End If
        '            Next
        '        End If
        '        Dim dsView As DataView = dt.DefaultView
        '        dsView.Sort = "_DateSort "
        '        dt = clsGet.ConvertDataViewToDataSet(dsView)
        '        dt.AcceptChanges()
        '        Grid.DataSource = dt
        '        Grid.DataBind()
        '        Dim lbTruck6 As Label = CType(gridProduct.Rows(i).FindControl("lbTruck6"), Label)
        '        Dim lbTruck810 As Label = CType(gridProduct.Rows(i).FindControl("lbTruck810"), Label)
        '        Dim lbTrailer As Label = CType(gridProduct.Rows(i).FindControl("lbTrailer"), Label)
        '        Dim lbTrailer2 As Label = CType(gridProduct.Rows(i).FindControl("lbTrailer2"), Label)
        '        Dim lbTransferSum As Label = CType(gridProduct.Rows(i).FindControl("lbTransferSum"), Label)
        '        Try
        '            lbTruck6.Text = FormatNumber(ViewState("SumTruck6"), 0)
        '            lbTruck810.Text = FormatNumber(ViewState("SumTruck810"), 0)
        '            lbTrailer.Text = FormatNumber(ViewState("SumTrailer"), 0)
        '            lbTrailer2.Text = FormatNumber(ViewState("SumTrailer2"), 0)
        '            lbTransferSum.Text = FormatNumber(ViewState("SumTransfer"), 0)
        '        Catch ex As Exception
        '            lbTruck6.Text = ViewState("SumTruck6")
        '            lbTruck810.Text = ViewState("SumTruck810")
        '            lbTrailer.Text = ViewState("SumTrailer")
        '            lbTrailer2.Text = ViewState("SumTrailer2")
        '            lbTransferSum.Text = ViewState("SumTransfer")
        '        End Try

        '        Session("TransferValue") = Nothing
        '        Session("IndexBulkProduct") = Nothing
        '        Session("ValueBulk") = Nothing
        '        If (dt.Rows.Count > 0) Then
        '            Dim lbStartActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartActualDate"), Label)
        '            Dim lbStartActual As Label = CType(gridProduct.Rows(i).FindControl("lbStartActual"), Label)
        '            Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
        '            Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)
        '            Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)
        '            Dim SumTruck As Double = 0.0
        '            For x As Integer = 0 To dt.Rows.Count - 1
        '                If (dt.Rows(x).Item("_M") & "" <> "") Then
        '                    Try
        '                        SumTruck += CDbl(dt.Rows(x).Item("_M"))
        '                    Catch ex As Exception

        '                    End Try

        '                End If
        '            Next
        '            txtTruckScale.Text = SumTruck.ToString("##################0.000")
        '            lbStartActualDate.Text = CDate(ClassFunctionGetData.CDateT(Grid.DataKeys(0).Values("_Date"))).ToString("dd/MM/yy")
        '            lbStartActual.Text = Grid.DataKeys(0).Values("_Time").ToString()
        '            lbStartStandardTime.Text = lbStartActual.Text
        '            lbStartStandardTimeDate.Text = lbStartActualDate.Text
        '            Dim lbStopActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopActualDate"), Label)
        '            Dim lbStopActual As Label = CType(gridProduct.Rows(i).FindControl("lbStopActual"), Label)
        '            'If (CInt(Grid.DataKeys(dt.Rows.Count - 1).Values("_Time2").ToString().Split(":")(0)) < CInt(Grid.DataKeys(dt.Rows.Count - 1).Values("_Time2").ToString().Split(":")(0))) Then
        '            lbStopActualDate.Text = CDate(ClassFunctionGetData.CDateT(Grid.DataKeys(dt.Rows.Count - 1).Values("_Date2"))).ToString("dd/MM/yy")
        '            'Else
        '            '    lbStopActualDate.Text = CDate(Grid.DataKeys(dt.Rows.Count - 1).Values("_Date")).AddDays(1).ToString("dd/MM/yy")
        '            'End If
        '            lbStopActual.Text = Grid.DataKeys(dt.Rows.Count - 1).Values("_Time2").ToString()

        '            Dim lbTargetQuatity As Label = CType(gridProduct.Rows(i).FindControl("lbTargetQuatity"), Label)
        '            Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
        '            Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
        '            Dim txtBL As TextBox = CType(gridProduct.Rows(i).FindControl("txtBL"), TextBox)


        '            Dim dsProduct As DataTable = clsGet.Get_StardardTimeBulk("'" & gridProduct.DataKeys(i).Values("Group_no") & "'", "S")
        '            Dim StardardTime = 0
        '            If (dsProduct.Rows.Count > 0) Then
        '                If (dsProduct.Rows(0).Item("StandardTime") & "" <> "") Then
        '                    If (txtBL.Text.Trim = "0") Or (txtBL.Text.Trim = "") Then
        '                        StardardTime = CInt(CDbl(lbTargetQuatity.Text) / CDbl((CDbl(CDbl(dsProduct.Rows(0).Item("StandardTime")) / 24).ToString("############0.00")) / 60).ToString("###########0.00"))
        '                    Else
        '                        StardardTime = CInt(CDbl(txtBL.Text) / CDbl((CDbl(CDbl(dsProduct.Rows(0).Item("StandardTime")) / 24).ToString("############0.00")) / 60).ToString("###########0.00"))
        '                    End If

        '                End If
        '            End If

        '            Dim Hour As Integer = StardardTime / 60
        '            Dim Minute As Integer = StardardTime Mod 60
        '            Dim HourPoint As Integer = CInt(lbStartStandardTime.Text.Split(":")(0))
        '            Dim MinutePoint As Integer = CInt(lbStartStandardTime.Text.Split(":")(1))

        '            Minute += MinutePoint
        '            Dim PlusHour As Integer = 0
        '            PlusHour = Minute / 60
        '            Minute = Minute Mod 60
        '            HourPoint += (Hour + PlusHour)

        '            Dim PlusDay As Integer = 0
        '            If (HourPoint > 23) Then
        '                PlusDay = HourPoint / 24
        '                HourPoint = HourPoint Mod 24
        '            End If
        '            If (PlusDay > 0) Then
        '                lbStopStandardTimeDate.Text = CDate(ClassFunctionGetData.CDateT(lbStartStandardTimeDate.Text)).AddDays(PlusDay).ToString("dd/MM/yy")
        '            Else
        '                lbStopStandardTimeDate.Text = lbStartStandardTimeDate.Text
        '            End If
        '            lbStopStandardTime.Text = HourPoint.ToString("00") & ":" & Minute.ToString("00")
        '        End If
        '        If Grid.Rows.Count > 0 Then
        '            Dim CheckBoxList1 As CheckBoxList = CType(gridProduct.Rows(i).FindControl("CheckBoxList1"), CheckBoxList)
        '            CheckBoxList1.Enabled = False
        '        End If
        '        Exit Sub
        '    End If
        'Next
    End Sub

    Private Function CreateDT() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("_Date", GetType(String))
        dt.Columns.Add("_Time", GetType(String))
        dt.Columns.Add("_Date2", GetType(String))
        dt.Columns.Add("_Time2", GetType(String))
        dt.Columns.Add("_DateSort", GetType(String))
        dt.Columns.Add("_STruck", GetType(String))
        dt.Columns.Add("_Truck6", GetType(String))
        dt.Columns.Add("_Truck810", GetType(String))
        dt.Columns.Add("_Trailer", GetType(String))
        dt.Columns.Add("_Trailer2", GetType(String))
        dt.Columns.Add("_M", GetType(String))
        dt.Columns.Add("_P", GetType(String))
        dt.Columns.Add("_B", GetType(String))
        dt.Columns.Add("_T", GetType(String))
        dt.Columns.Add("_C", GetType(String))
        dt.Columns.Add("_R", GetType(String))
        dt.Columns.Add("_L", GetType(String))
        dt.Columns.Add("_Remark", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub btnDelay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelay.Click
        Session("DelayEdit") = Nothing
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditDelay').src = '../FormPopup/CauseOfDelay.aspx';", True)
        ModalPopupExtender4.Show()
    End Sub

    Private Sub btnDelayLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelayLoad.Click
        'ทำการโหลด Remark Delay
        System.Threading.Thread.Sleep(750)
        gridDelay.DataSource = Session("Delay")
        gridDelay.DataBind()
    End Sub
    Protected Sub gridTransfer_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs)
        'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('" & sender.GetType().ToString() & "');", True)

        Dim gvTmp As GridView = sender
        Dim rowGridItem As GridViewRow = CType(gvTmp.NamingContainer, GridViewRow)
        ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('" & rowGridItem.NamingContainer.GetType().ToString() & "')", True)


        Dim txtScale As TextBox = CType(rowGridItem.FindControl("txtTruckScale"), TextBox)

        Dim dtTmp As DataTable = CType(ViewState("TruckScale"), DataTable)
        dtTmp.Rows(e.RowIndex).Delete()
        dtTmp.AcceptChanges()
        ViewState("TruckScale") = dtTmp
        gvTmp.DataSource = dtTmp
        gvTmp.DataBind()
        If (productWeightTotal <> 0) Then
            txtScale.Text = productWeightTotal.ToString("N", numberFormat).Replace(",", "")
        Else
            txtScale.Text = String.Empty
        End If

        Dim reptTruck As Repeater = CType(rowGridItem.FindControl("reptTruckCount"), Repeater)
        Dim newCountTruck As DataTable = CType(ViewState("countTruckType"), DataTable)

        newCountTruck.Rows(e.RowIndex).Delete()
        newCountTruck.AcceptChanges()
        ViewState("countTruckType") = newCountTruck

        Dim gridProRow As String = rowGridItem.RowIndex.ToString()
        Dim sessName As String = "truckTypeGroup" & gridProRow
        Session("TruckScale" & gridProRow) = dtTmp
        Session(sessName) = newCountTruck
        ' Session(sessName & rowIndex) = dtTruckTypeCount

        ' LINQ Expression ใช้สำหรับ count Truck Type โดย Gruup By TruckType
        Dim dtEnum As IEnumerable(Of DataRow) = newCountTruck.AsEnumerable()
        Dim disT = From t In dtEnum Where t.Item("TruckType").ToString() <> "" _
               Group t By Key = t.Item("TruckType") Into Group Select TruckType = Key, TotalCount = Group.Sum(Function(p) p("cntType"))
        disT = From t In disT Where t.TotalCount > 0 Select t
        'If (disT IsNot Nothing) Then
        reptTruck.DataSource = disT
        reptTruck.DataBind()
        ' End If

    End Sub
    Protected Sub gridTransfer_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
        Dim gridTransfer = DirectCast(sender, GridView)
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridTransfer.PageIndex <> 0) Then
            Index = Index Mod (gridTransfer.PageIndex * 10)
        End If
        If e.CommandName = "cmdedit" Then
            'Session("IndexBulkProduct") = Index
            'Session("ValueBulk") = gridTransfer.DataKeys(Index).Values("_Date") & "$" & gridTransfer.DataKeys(Index).Values("_Time") & "$" & gridTransfer.DataKeys(Index).Values("_M") & "$" & gridTransfer.DataKeys(Index).Values("_P") & "$" & gridTransfer.DataKeys(Index).Values("_B") & "$" & gridTransfer.DataKeys(Index).Values("_T") & "$" & gridTransfer.DataKeys(Index).Values("_C") & "$" & gridTransfer.DataKeys(Index).Values("_Remark") & "$" & gridTransfer.DataKeys(Index).Values("_Truck6") & "$" & gridTransfer.DataKeys(Index).Values("_Truck810") & "$" & gridTransfer.DataKeys(Index).Values("_Trailer") & "$" & gridTransfer.DataKeys(Index).Values("_Trailer2") & "$" & gridTransfer.DataKeys(Index).Values("_R") & "$" & gridTransfer.DataKeys(Index).Values("_L") & "$" & gridTransfer.DataKeys(Index).Values("_Date2") & "$" & gridTransfer.DataKeys(Index).Values("_Time2")
            'For i As Integer = 0 To gridProduct.Rows.Count - 1
            '    Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
            '    If (gridTransfer.ClientID.Replace("gridTransfer", "") = hdfgrid.ClientID.Replace("hdfgrid", "")) Then
            '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditTransfer').src = '../FormPopup/frm_Transfer_Product.aspx';", True)
            '        Session("hdfgrid") = hdfgrid.Value & "$" & gridTransfer.ClientID.Replace("gridTransfer", "")
            '        ModalPopupExtender1.Show()
            '        Exit Sub
            '    End If
            'Next

        ElseIf e.CommandName = "cmddelete" Then
            'Dim dt As DataTable = CreateDT()
            'For m As Integer = 0 To gridTransfer.Rows.Count - 1
            '    If (m <> Index) Then
            '        Dim drN As DataRow = dt.NewRow
            '        drN.Item("_Date") = gridTransfer.DataKeys(m).Values("_Date")
            '        drN.Item("_Time") = gridTransfer.DataKeys(m).Values("_Time")
            '        drN.Item("_Date2") = gridTransfer.DataKeys(m).Values("_Date2")
            '        drN.Item("_Time2") = gridTransfer.DataKeys(m).Values("_Time2")
            '        drN.Item("_DateSort") = gridTransfer.DataKeys(m).Values("_DateSort")
            '        drN.Item("_STruck") = gridTransfer.DataKeys(m).Values("_STruck")
            '        drN.Item("_Truck6") = gridTransfer.DataKeys(m).Values("_Truck6")
            '        drN.Item("_Truck810") = gridTransfer.DataKeys(m).Values("_Truck810")
            '        drN.Item("_Trailer") = gridTransfer.DataKeys(m).Values("_Trailer")
            '        drN.Item("_Trailer2") = gridTransfer.DataKeys(m).Values("_Trailer2")
            '        drN.Item("_M") = gridTransfer.DataKeys(m).Values("_M")
            '        drN.Item("_P") = gridTransfer.DataKeys(m).Values("_P")
            '        drN.Item("_B") = gridTransfer.DataKeys(m).Values("_B")
            '        drN.Item("_T") = gridTransfer.DataKeys(m).Values("_T")
            '        drN.Item("_C") = gridTransfer.DataKeys(m).Values("_C")
            '        drN.Item("_L") = gridTransfer.DataKeys(m).Values("_L")
            '        drN.Item("_R") = gridTransfer.DataKeys(m).Values("_R")
            '        drN.Item("_Remark") = gridTransfer.DataKeys(m).Values("_Remark")
            '        dt.Rows.Add(drN)
            '        dt.AcceptChanges()
            '    End If
            'Next
            'gridTransfer.DataSource = dt
            'gridTransfer.DataBind()

            'Dim SumTruck As Double = 0.0
            'For x As Integer = 0 To dt.Rows.Count - 1
            '    If (dt.Rows(x).Item("_M") & "" <> "") Then
            '        Try
            '            SumTruck += CDbl(dt.Rows(x).Item("_M"))
            '        Catch ex As Exception

            '        End Try

            '    End If
            'Next
            'For i As Integer = 0 To gridProduct.Rows.Count - 1
            '    Dim CheckBoxList1 As CheckBoxList = CType(gridProduct.Rows(i).FindControl("CheckBoxList1"), CheckBoxList)
            '    If (CheckBoxList1.ClientID.Replace("CheckBoxList1", "") = gridTransfer.ClientID.Replace("gridTransfer", "")) Then
            '        Try
            '            Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)
            '            txtTruckScale.Text = SumTruck.ToString("##################0.000")
            '        Catch ex As Exception

            '        End Try

            '        If (gridTransfer.Rows.Count = 0) Then
            '            CheckBoxList1.Enabled = True
            '        End If
            '    End If
            'Next
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        LoadBOoking()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Protected Sub txtBL_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim txtBL = DirectCast(sender, TextBox)
        For i As Integer = 0 To gridProduct.Rows.Count - 1
            Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
            If (txtBL.ClientID.Replace("txtBL", "") = Grid.ClientID.Replace("gridTransfer", "")) Then
                If (Grid.Rows.Count > 0) Then
                    Dim lbTargetQuatity As Label = CType(gridProduct.Rows(i).FindControl("lbTargetQuatity"), Label)
                    Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
                    Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
                    Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
                    Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)

                    Dim dsProduct As DataTable = clsGet.Get_StardardTimeBulk("'" & gridProduct.DataKeys(i).Values("Group_no") & "'", "S")
                    Dim StardardTime = 0
                    If (dsProduct.Rows.Count > 0) Then
                        If (dsProduct.Rows(0).Item("StandardTime") & "" <> "") Then
                            If (txtBL.Text.Trim = "0") Or (txtBL.Text.Trim = "") Then
                                StardardTime = CInt(CDbl(lbTargetQuatity.Text) / CDbl((CDbl(CDbl(dsProduct.Rows(0).Item("StandardTime")) / 24).ToString("############0.00")) / 60).ToString("###########0.00"))
                            Else
                                StardardTime = CInt(CDbl(txtBL.Text) / CDbl((CDbl(CDbl(dsProduct.Rows(0).Item("StandardTime")) / 24).ToString("############0.00")) / 60).ToString("###########0.00"))
                            End If

                        End If
                    End If

                    Dim Hour As Integer = StardardTime / 60
                    Dim Minute As Integer = StardardTime Mod 60
                    Dim HourPoint As Integer = CInt(lbStartStandardTime.Text.Split(":")(0))
                    Dim MinutePoint As Integer = CInt(lbStartStandardTime.Text.Split(":")(1))

                    Minute += MinutePoint
                    Dim PlusHour As Integer = 0
                    PlusHour = Minute / 60
                    Minute = Minute Mod 60
                    HourPoint += (Hour + PlusHour)

                    Dim PlusDay As Integer = 0
                    If (HourPoint > 23) Then
                        PlusDay = HourPoint / 24
                        HourPoint = HourPoint Mod 24
                    End If
                    If (PlusDay > 0) Then
                        lbStopStandardTimeDate.Text = CDate(ClassFunctionGetData.CDateT(lbStartStandardTimeDate.Text)).AddDays(PlusDay).ToString("dd/MM/yy")
                    Else
                        lbStopStandardTimeDate.Text = lbStartStandardTimeDate.Text
                    End If
                    lbStopStandardTime.Text = HourPoint.ToString("00") & ":" & Minute.ToString("00")
                End If
            End If
        Next
    End Sub

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim User_Modify As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        Dim Status As String = ""
        Dim dtStatus As DataTable = clsGet.Get_Load_Unload_Vessel(ViewState("EditBooking"))
        If (dtStatus.Rows.Count > 0) Then
            Status = dtStatus.Rows(0).Item("Status") & ""
        End If
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        Dim start As String = ""
        clsFc.DeleteLoad_Unload_All(ViewState("EditBooking"), conn, tran)
        If (clsFc.InsertLoad_Unload_Vessel_Bulk(ViewState("EditBooking"), txtThirdParty.Text, txtDepartActualDate.Text, txtDepartAutualTime.Text, lbTugBefore.Text, lbTugAfter.Text, ddlWharfIn.SelectedValue, txtFenderIn.Text, txtCompany.Text, txtEmployeeIn.Text, txtFOR.Text, txtAFT.Text, txtInitialCompany.Text, txtInitialDateFrom.Text, txtInitialDateTo.Text, txtInitialStart.Text, txtInitialEnd.Text, txtFOR_Out.Text, txtAFT_Out.Text, txtFinalCompany.Text, txtFinalDateFrom.Text, txtFinalDateTo.Text, txtFinalStart.Text, txtFinalEnd.Text, ddlWharfOut.SelectedValue, txtFenderOut.Text, txtEmployeeOut.Text, txtNORTender.Text, txtNORTenderTime.Text, Status, conn, tran) > 0) Then
            For i As Integer = 0 To gridProduct.Rows.Count - 1
                Dim txtBL As TextBox = CType(gridProduct.Rows(i).FindControl("txtBL"), TextBox)
                Dim txtDraftSurvey As TextBox = CType(gridProduct.Rows(i).FindControl("txtDraftSurvey"), TextBox)
                Dim txtManifest As TextBox = CType(gridProduct.Rows(i).FindControl("txtManifest"), TextBox)
                Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)

                Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
                Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)
                Dim lbStartActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartActualDate"), Label)
                Dim lbStartActual As Label = CType(gridProduct.Rows(i).FindControl("lbStartActual"), Label)
                Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
                Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
                Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
                Dim lbStopActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopActualDate"), Label)
                Dim lbStopActual As Label = CType(gridProduct.Rows(i).FindControl("lbStopActual"), Label)

                If (start = "") Then
                    Try
                        start = lbStartActualDate.Text
                        start = start.Substring(0, 2) & " " & GetNameMonth(start.Substring(3, 2)) & " " & CInt("20" & start.Substring(6, 2))
                        start &= " " & lbStartActual.Text
                    Catch ex As Exception

                    End Try

                End If
                If (clsFc.InsertLoad_Unload_Product_Bulk(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), lbStartStandardTimeDate.Text, lbStartStandardTime.Text, lbStartActualDate.Text, lbStartActual.Text, lbStopStandardTimeDate.Text, lbStopStandardTime.Text, lbStopActualDate.Text, lbStopActual.Text, hdfgrid.Value, txtBL.Text, txtDraftSurvey.Text, txtManifest.Text, txtTruckScale.Text, gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                    condition = False
                    Exit For
                Else
                    Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
                    For m As Integer = 0 To Grid.Rows.Count - 1
                        If (clsFc.InsertLoad_Unload_Product_BulkValue(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), Grid.DataKeys(m).Values("_Date"), Grid.DataKeys(m).Values("_DateSort"), Grid.DataKeys(m).Values("_Time"), Grid.DataKeys(m).Values("_STruck"), Grid.DataKeys(m).Values("_Truck6"), Grid.DataKeys(m).Values("_Truck810"), Grid.DataKeys(m).Values("_Trailer"), Grid.DataKeys(m).Values("_Trailer2"), Grid.DataKeys(m).Values("_M"), Grid.DataKeys(m).Values("_P"), Grid.DataKeys(m).Values("_B"), Grid.DataKeys(m).Values("_T"), Grid.DataKeys(m).Values("_C"), Grid.DataKeys(m).Values("_L"), Grid.DataKeys(m).Values("_R"), Grid.DataKeys(m).Values("_Remark"), Grid.DataKeys(m).Values("_Date2"), Grid.DataKeys(m).Values("_Time2"), gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next
                End If
            Next

            Dim dtDelay As DataTable = Session("Delay")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Delay(ViewState("EditBooking"), dr.Item("Date_From"), dr.Item("Date_To"), dr.Item("Time_From"), dr.Item("Time_To"), dr.Item("Cause_Delay"), dr.Item("Delay_Time"), dr.Item("Cause_Code"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            dtDelay = Session("Remark")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Remark(ViewState("EditBooking"), dr.Item("Remark"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            If (clsFc.InsertLoad_Unload_Addition(ViewState("EditBooking"), "", "", "", "", txtWater.Text, "", "", "", "", "", "", "", txtElectricity.Text, txtHopper.Text, txtHopperFrom.Text, txtHopperTo.Text, txtHopperDateFrom.Text, txtHopperDateTo.Text, conn, tran) < 1) Then
                condition = False
            End If
        Else
            condition = False
        End If

        If (condition) Then
            clsDB.CommitTran(tran)
            LoadBOoking()
            ViewState("Load") = "Not"
            If Not CBool(ViewState("Start")) Then
                Dim str As String = ""
                Dim dtBOoking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
                Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
                Dim Berth As String = ""
                If (dtLogIn.Rows.Count > 0) Then
                    Try
                        Berth = dtLogIn.Rows(0).Item("Berthing_Date") & " " & dtLogIn.Rows(0).Item("Berthing_TimeTo")
                    Catch ex As Exception

                    End Try

                End If
                str = GenBody("เริ่มดำเนินการขนถ่าย", ViewState("EditBooking"), dtBOoking.Rows(0).Item("MAgent_no") & "-" & dtBOoking.Rows(0).Item("MAgent_name"), dtBOoking.Rows(0).Item("Vehicle_no") & "-" & dtBOoking.Rows(0).Item("Vehicle_Text"), dtBOoking.Rows(0).Item("Date_From") & "-" & dtBOoking.Rows(0).Item("Date_To"), Berth, start, "", "")
                SendMail(ViewState("EditBooking"), "CUSTOMER", str)
                ViewState("Start") = True
            End If
            Timer1_Tick(sender, e)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกข้อมูลสำเร็จ');", True)
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub btnLoadIndex_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoadIndex.Click
        LoadEdit(Session("Index_For_Save"))

        'Dim Index As Integer = CInt(Session("Index_For_Save"))
        'Session("Index_For_Save") = Nothing
        'ViewState("StandardTimeProductLast") = ""
        'ViewState("StandardTimeProductLastDate") = ""
        'ViewState("StopActual") = ""
        'ViewState("EditBooking") = gridItem.DataKeys(Index).Values("Booking_no")
        'lbVessel.Text = gridItem.DataKeys(Index).Values("Vehicle_Text")

        'Dim dt As DataTable = clsGet.Get_Booking_ProductOperationBulk(ViewState("EditBooking"))
        'gridProduct.DataSource = dt
        'gridProduct.DataBind()

        'dt = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
        'If (dt.Rows.Count = 1) Then
        '    If (dt.Rows(0).Item("Berthing_TimeTo") & "" <> "") Then
        '        lbarrived.Text = ConvertDate(dt.Rows(0).Item("Anchor_Date")) & " " & dt.Rows(0).Item("Anchor_Time")
        '        lbNOR.Text = ConvertDate(dt.Rows(0).Item("Anchor_Date")) & " " & dt.Rows(0).Item("Anchor_Time")
        '        lbPOB.Text = ConvertDate(dt.Rows(0).Item("POB_Date")) & " " & dt.Rows(0).Item("POB_Time")
        '        lbAccept.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date")) & " " & dt.Rows(0).Item("Berthing_TimeTo")
        '        lbFirstling.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date")) & " " & dt.Rows(0).Item("Berthing_TimeFrom")
        '        lbBerthedStandardDate.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date"))
        '        lbBerthedStandard.Text = dt.Rows(0).Item("Berthing_TimeTo")
        '        lbBerthedDate.Text = ConvertDate(dt.Rows(0).Item("Berthing_Date"))
        '        lbBerthed.Text = dt.Rows(0).Item("Berthing_TimeTo")

        '        lbPilotNo.Text = dt.Rows(0).Item("Pilot") & ""
        '    Else
        '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เรือยังไม่ได้เข้าเทียบท่า!!');", True)
        '        Exit Sub
        '    End If
        'Else
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เรือยังไม่ได้เข้าเทียบท่า!!');", True)
        '    Exit Sub
        'End If



        'Dim dtDelay As DataTable = clsGet.Get_Load_Unload_Delay(ViewState("EditBooking"))
        'If (dtDelay.Rows.Count = 0) Then
        '    dtDelay = CreateTabelDelay()
        'End If

        ''ยังไม่ทำการ BInd ค่ากรณีที่เคย save ไว้ ตอน BIne ที่Bind   TUg_Before , Tug_After ด้วย
        'dt = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "I", "")
        'Dim Tug_Name As String = ""
        'For Each dr As DataRow In dt.Rows
        '    If (dr.Item("Tug_Name") & "" <> "") Then
        '        If (Tug_Name = "") Then
        '            Tug_Name = dr.Item("Tug_Name")
        '        Else
        '            Tug_Name &= "," & dr.Item("Tug_Name")
        '        End If
        '    End If
        'Next
        'lbTugBefore.Text = Tug_Name
        'dt = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "O", "")
        'Tug_Name = ""
        'For Each dr As DataRow In dt.Rows
        '    If (dr.Item("Tug_Name") & "" <> "") Then
        '        If (Tug_Name = "") Then
        '            Tug_Name = dr.Item("Tug_Name")
        '        Else
        '            Tug_Name &= "," & dr.Item("Tug_Name")
        '        End If
        '    End If
        'Next
        'lbTugAfter.Text = Tug_Name

        'Session("Delay") = dtDelay
        'gridDelay.DataSource = dtDelay
        'gridDelay.DataBind()


        'PanelBookingItem.Visible = False
        'PanelShipLoading.Visible = True
    End Sub

    Private Sub btnLoadIndex2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoadIndex2.Click
        LoadBOoking()
    End Sub
    Dim truckTotalCount As Integer = 0
    Dim productWeightTotal As Double = 0
    Dim sumTotalTruck As Integer = 0
    Dim packageCount As Integer = 0
    Dim bagCount As Integer = 0
    Dim drumCount As Integer = 0
    Dim pcsCount As Integer = 0
    Dim litterCont As Integer = 0
    Dim rollCount As Integer = 0
    Public Sub gridTransfer_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim dinf As New CultureInfo("en-US")
            ' Try
            'Dim dateInText As String = e.Row.Cells(0).Text
            'Dim dateIn As Date = Date.ParseExact(dateInText, "dd/MM/yyyy", dinf)
            'e.Row.Cells(0).Text = dateIn.ToString("dd MMM yyyy", dinf)

            'Dim dateOutText As String = e.Row.Cells(2).Text
            'Dim dateOut As Date = Date.ParseExact(dateInText, "dd/MM/yyyy", dinf)
            'e.Row.Cells(2).Text = dateOut.ToString("dd MMM yyyy", dinf)
            Dim db As New DB_Class()
            Try
                Dim truckScaleIdIn As String = e.Row.Cells(0).Text
                db.queryString = "select * from Truck_Scale where TruckScaleID='" & truckScaleIdIn & "'"
                Dim dtDateIn As DataTable = db.getTable("dateIn")
                Dim dateTimeIn As String = dtDateIn.Rows(0)("Date_Scale_IN").ToString() & " " & dtDateIn.Rows(0)("Time_Scale_IN").ToString()
                Dim date1 As Date = Date.ParseExact(dateTimeIn, "dd/MM/yyyy HH:mm:ss", dinf)


                Dim truckScaleIdOut As String = e.Row.Cells(2).Text
                db.queryString = "select * from Truck_Scale where TruckScaleID='" & truckScaleIdOut & "'"
                Dim dtDateOut As DataTable = db.getTable("dateOut")
                Dim dateTimeOut As String = dtDateOut.Rows(0)("Date_Scale_OUT").ToString() & " " & dtDateOut.Rows(0)("Time_Scale_OUT").ToString()
                Dim date2 As Date = Date.ParseExact(dateTimeOut, "dd/MM/yyyy HH:mm:ss", dinf)

                If (DateDiff(DateInterval.Minute, date2, date1) > 0) Then
                    Dim dateTmp As Date = date1
                    date1 = date2
                    date2 = dateTmp
                End If

                e.Row.Cells(0).Text = date1.ToString("dd MMM yyyy", dinf)
                e.Row.Cells(1).Text = date1.ToString("HH:mm", dinf)

                e.Row.Cells(2).Text = date2.ToString("dd MMM yyyy", dinf)
                e.Row.Cells(3).Text = date2.ToString("HH:mm", dinf)
            Catch ex As Exception
                Dim dateTimeIn As String = e.Row.Cells(0).Text
                Dim date1 As Date = Date.ParseExact(dateTimeIn, "dd/MM/yyyy HH:mm", dinf)
                Dim dateTimeOut As String = e.Row.Cells(2).Text
                Dim date2 As Date = Date.ParseExact(dateTimeOut, "dd/MM/yyyy HH:mm", dinf)

                e.Row.Cells(0).Text = date1.ToString("dd MMM yyyy", dinf)
                e.Row.Cells(1).Text = date1.ToString("HH:mm", dinf)

                e.Row.Cells(2).Text = date2.ToString("dd MMM yyyy", dinf)
                e.Row.Cells(3).Text = date2.ToString("HH:mm", dinf)
            End Try
            


            truckTotalCount += CInt(e.Row.Cells(4).Text)
            e.Row.Cells(5).Text = truckTotalCount.ToString()

            Dim proWeight As Double = CDbl(e.Row.Cells(6).Text)
            productWeightTotal += proWeight
            e.Row.Cells(6).Text = proWeight.ToString("N", numberFormat)
            e.Row.Cells(7).Text = productWeightTotal.ToString("N", numberFormat)

            Dim gv As GridView = sender
            Dim gvrPro As GridViewRow = CType(gv.NamingContainer, GridViewRow)
            Dim textTmp As TextBox = CType(gvrPro.FindControl("txtTruckScale"), TextBox)
            textTmp.Text = productWeightTotal.ToString("N", numberFormat).Replace(",", "")

            Dim gridProRow As String = Session("gridProRow")
            Dim dtTruckScale As DataTable = Session("TruckScale" & gridProRow)
            Try
                e.Row.Cells(14).Text = dtTruckScale.Rows(e.Row.RowIndex)("package").ToString()
                packageCount += CInt(e.Row.Cells(14).Text)
                e.Row.Cells(15).Text = packageCount.ToString()
            Catch ex As Exception

            End Try

            Try
                e.Row.Cells(8).Text = dtTruckScale.Rows(e.Row.RowIndex)("bag").ToString()
                bagCount += CInt(e.Row.Cells(8).Text)
                e.Row.Cells(9).Text = bagCount.ToString()
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(10).Text = dtTruckScale.Rows(e.Row.RowIndex)("drum").ToString()
                drumCount += CInt(e.Row.Cells(10).Text)
                e.Row.Cells(11).Text = drumCount.ToString()
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(16).Text = dtTruckScale.Rows(e.Row.RowIndex)("pcs").ToString()
                pcsCount += CInt(e.Row.Cells(16).Text)
                e.Row.Cells(17).Text = pcsCount.ToString()
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(12).Text = dtTruckScale.Rows(e.Row.RowIndex)("litter").ToString()
                litterCont += CInt(e.Row.Cells(12).Text)
                e.Row.Cells(13).Text = litterCont.ToString()
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(18).Text = dtTruckScale.Rows(e.Row.RowIndex)("roll").ToString()
                rollCount += CInt(e.Row.Cells(18).Text)
                e.Row.Cells(19).Text = rollCount.ToString()
            Catch ex As Exception

            End Try
            'Catch ex As Exception

            ' End Try

            ' e.Row.Cells(0).Text = dateTime.ToString("dd MMM yyyy")

            'If (e.Row.RowIndex = 0) Then
            '    Try
            '        ViewState("SumTruck6") = CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Truck6") & "")
            '        ViewState("SumTruck810") = CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Truck810") & "")
            '        ViewState("SumTrailer") = CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Trailer") & "")
            '        ViewState("SumTrailer2") = CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Trailer2") & "")
            '        ViewState("SumTransfer") = CInt(ViewState("SumTruck6")) + CInt(ViewState("SumTruck810")) + CInt(ViewState("SumTrailer")) + CInt(ViewState("SumTrailer2"))
            '    Catch ex As Exception
            '        ViewState("SumTruck6") = 0
            '        ViewState("SumTruck810") = 0
            '        ViewState("SumTrailer") = 0
            '        ViewState("SumTrailer2") = 0
            '        ViewState("SumTransfer") = 0
            '    End Try

            '    Try
            '        e.Row.Cells(5).Text = FormatNumber(e.Row.Cells(4).Text, 0)
            '        e.Row.Cells(4).Text = FormatNumber(e.Row.Cells(4).Text, 0)
            '        ViewState("2") = CInt(e.Row.Cells(4).Text)
            '    Catch ex As Exception
            '        ViewState("2") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(7).Text = FormatNumber(e.Row.Cells(6).Text, 3)
            '        e.Row.Cells(6).Text = FormatNumber(e.Row.Cells(6).Text, 3)
            '        ViewState("4") = CDbl(e.Row.Cells(6).Text)
            '    Catch ex As Exception
            '        ViewState("4") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(9).Text = FormatNumber(e.Row.Cells(8).Text)
            '        e.Row.Cells(8).Text = FormatNumber(e.Row.Cells(8).Text)
            '        ViewState("6") = CDbl(e.Row.Cells(8).Text)
            '    Catch ex As Exception
            '        ViewState("6") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(11).Text = FormatNumber(e.Row.Cells(10).Text)
            '        e.Row.Cells(10).Text = FormatNumber(e.Row.Cells(10).Text)
            '        ViewState("8") = CDbl(e.Row.Cells(10).Text)
            '    Catch ex As Exception
            '        ViewState("8") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(13).Text = FormatNumber(e.Row.Cells(12).Text)
            '        e.Row.Cells(12).Text = FormatNumber(e.Row.Cells(12).Text)
            '        ViewState("10") = CDbl(e.Row.Cells(12).Text)
            '    Catch ex As Exception
            '        ViewState("10") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(15).Text = FormatNumber(e.Row.Cells(14).Text)
            '        e.Row.Cells(14).Text = FormatNumber(e.Row.Cells(14).Text)
            '        ViewState("12") = CDbl(e.Row.Cells(14).Text)
            '    Catch ex As Exception
            '        ViewState("12") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(17).Text = FormatNumber(e.Row.Cells(16).Text)
            '        e.Row.Cells(16).Text = FormatNumber(e.Row.Cells(16).Text)
            '        ViewState("14") = CDbl(e.Row.Cells(16).Text)
            '    Catch ex As Exception
            '        ViewState("14") = 0.0
            '    End Try
            '    Try
            '        e.Row.Cells(19).Text = FormatNumber(e.Row.Cells(18).Text)
            '        e.Row.Cells(18).Text = FormatNumber(e.Row.Cells(18).Text)
            '        ViewState("16") = CDbl(e.Row.Cells(18).Text)
            '    Catch ex As Exception
            '        ViewState("16") = 0.0
            '    End Try
            'ElseIf (e.Row.RowIndex > 0) Then
            '    ViewState("SumTruck6") = CInt(ViewState("SumTruck6")) + CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Truck6") & "")
            '    ViewState("SumTruck810") = CInt(ViewState("SumTruck810")) + CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Truck810") & "")
            '    ViewState("SumTrailer") = CInt(ViewState("SumTrailer")) + CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Trailer") & "")
            '    ViewState("SumTrailer2") = CInt(ViewState("SumTrailer2")) + CInt(DirectCast(sender, GridView).DataKeys(e.Row.RowIndex).Values("_Trailer2") & "")
            '    ViewState("SumTransfer") = CInt(ViewState("SumTruck6")) + CInt(ViewState("SumTruck810")) + CInt(ViewState("SumTrailer")) + CInt(ViewState("SumTrailer2"))
            '    Try
            '        e.Row.Cells(5).Text = FormatNumber((CInt(e.Row.Cells(4).Text) + CInt(ViewState("2"))), 0)
            '        e.Row.Cells(4).Text = FormatNumber(e.Row.Cells(4).Text, 0)
            '        ViewState("2") = e.Row.Cells(5).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(7).Text = FormatNumber((CDbl(e.Row.Cells(6).Text) + CDbl(ViewState("4"))), 3)
            '        e.Row.Cells(6).Text = FormatNumber(e.Row.Cells(6).Text, 3)
            '        ViewState("4") = e.Row.Cells(7).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(9).Text = FormatNumber((CDbl(e.Row.Cells(8).Text) + CDbl(ViewState("6"))))
            '        e.Row.Cells(8).Text = FormatNumber(e.Row.Cells(8).Text)
            '        ViewState("6") = e.Row.Cells(9).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(11).Text = FormatNumber((CDbl(e.Row.Cells(10).Text) + CDbl(ViewState("8"))))
            '        e.Row.Cells(10).Text = FormatNumber(e.Row.Cells(10).Text)
            '        ViewState("8") = e.Row.Cells(11).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(13).Text = FormatNumber((CDbl(e.Row.Cells(12).Text) + CDbl(ViewState("10"))))
            '        e.Row.Cells(12).Text = FormatNumber(e.Row.Cells(12).Text)
            '        ViewState("10") = e.Row.Cells(13).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(15).Text = FormatNumber((CDbl(e.Row.Cells(14).Text) + CDbl(ViewState("12"))))
            '        e.Row.Cells(14).Text = FormatNumber(e.Row.Cells(14).Text)
            '        ViewState("12") = e.Row.Cells(15).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(17).Text = FormatNumber((CDbl(e.Row.Cells(16).Text) + CDbl(ViewState("14"))))
            '        e.Row.Cells(16).Text = FormatNumber(e.Row.Cells(16).Text)
            '        ViewState("14") = e.Row.Cells(17).Text
            '    Catch ex As Exception

            '    End Try
            '    Try
            '        e.Row.Cells(19).Text = FormatNumber((CDbl(e.Row.Cells(18).Text) + CDbl(ViewState("16"))))
            '        e.Row.Cells(18).Text = FormatNumber(e.Row.Cells(18).Text)
            '        ViewState("16") = e.Row.Cells(19).Text
            '    Catch ex As Exception

            '    End Try

            'End If
        End If
    End Sub
    Protected Sub gridTransfer_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
        truckTotalCount = 0
        productWeightTotal = 0
        sumTotalTruck = 0
        packageCount = bagCount = drumCount = pcsCount = litterCont = rollCount = 0
    End Sub
    Protected Sub gridTransfer_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
        Session("gridTransfer") = sender
        Session("gridTransferRowEdit") = e.NewEditIndex
        Dim gvTmp As GridView = sender
        Dim rowGridPro As GridViewRow = CType(gvTmp.NamingContainer, GridViewRow)
        Dim curRowGridPro As String = rowGridPro.RowIndex.ToString()
        Session("gridProRow") = curRowGridPro
        Dim hdfGridProduct As HtmlInputHidden = CType(rowGridPro.FindControl("hdfgrid"), HtmlInputHidden)
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditTransfer').src = '../FormPopup/frm_Transfer_Product.aspx';", True)
        Session("hdfgrid") = hdfGridProduct.Value
        ModalPopupExtender1.Show()
        'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('" & hdfGridProduct.Value & "');", True)
    End Sub
    Private Sub btnRemarkLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemarkLoad.Click
        System.Threading.Thread.Sleep(750)
        gridRemark.DataSource = Session("Remark")
        gridRemark.DataBind()
    End Sub

    Private Sub gridDelay_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridDelay.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "cmdedit" Then
            Session("DelayEdit") = Index
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditDelay').src = '../FormPopup/CauseOfDelay.aspx';", True)
            ModalPopupExtender4.Show()
        ElseIf (e.CommandName = "cmddelete") Then
            Dim dt As DataTable = Session("Delay")
            dt.Rows(Index).Delete()
            dt.AcceptChanges()
            Session("Delay") = dt
        End If
    End Sub

    Private Sub gridDelay_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridDelay.RowEditing

    End Sub

    Private Sub gridRemark_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridRemark.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "cmdedit" Then
            Session("RemarkEdit") = Index
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditRemark').src = '../FormPopup/CauseOfRemark.aspx';", True)
            ModalPopupExtender6.Show()
        ElseIf (e.CommandName = "cmddelete") Then
            Dim dt As DataTable = Session("Remark")
            dt.Rows(Index).Delete()
            dt.AcceptChanges()
            Session("Remark") = dt
            gridRemark.DataSource = dt
            gridRemark.DataBind()
        End If
    End Sub

    Private Sub gridRemark_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridRemark.RowEditing

    End Sub

    Private Sub btnRemark_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemark.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditRemark').src = '../FormPopup/CauseOfRemark.aspx';", True)
        ModalPopupExtender6.Show()
    End Sub

    Private Sub btnCheck_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheck.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim User_Modify As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        Application.Lock()
        conn.Open()
        Dim A_Code As String = clsDB.GeneratorID(conn, "Action_Operation")
        tran = clsDB.BeginTran(conn)

        clsFc.DeleteLoad_Unload_All(ViewState("EditBooking"), conn, tran)
        If (clsFc.InsertLoad_Unload_Vessel_Bulk(ViewState("EditBooking"), txtThirdParty.Text, txtDepartActualDate.Text, txtDepartAutualTime.Text, lbTugBefore.Text, lbTugAfter.Text, ddlWharfIn.SelectedValue, txtFenderIn.Text, txtCompany.Text, txtEmployeeIn.Text, txtFOR.Text, txtAFT.Text, txtInitialCompany.Text, txtInitialDateFrom.Text, txtInitialDateTo.Text, txtInitialStart.Text, txtInitialEnd.Text, txtFOR_Out.Text, txtAFT_Out.Text, txtFinalCompany.Text, txtFinalDateFrom.Text, txtFinalDateTo.Text, txtFinalStart.Text, txtFinalEnd.Text, ddlWharfOut.SelectedValue, txtFenderOut.Text, txtEmployeeOut.Text, txtNORTender.Text, txtNORTenderTime.Text, "C", conn, tran) > 0) Then
            For i As Integer = 0 To gridProduct.Rows.Count - 1
                Dim txtBL As TextBox = CType(gridProduct.Rows(i).FindControl("txtBL"), TextBox)
                Dim txtDraftSurvey As TextBox = CType(gridProduct.Rows(i).FindControl("txtDraftSurvey"), TextBox)
                Dim txtManifest As TextBox = CType(gridProduct.Rows(i).FindControl("txtManifest"), TextBox)
                Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)

                Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
                Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)
                Dim lbStartActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartActualDate"), Label)
                Dim lbStartActual As Label = CType(gridProduct.Rows(i).FindControl("lbStartActual"), Label)
                Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
                Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
                Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
                Dim lbStopActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopActualDate"), Label)
                Dim lbStopActual As Label = CType(gridProduct.Rows(i).FindControl("lbStopActual"), Label)

                If (clsFc.InsertLoad_Unload_Product_Bulk(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), lbStartStandardTimeDate.Text, lbStartStandardTime.Text, lbStartActualDate.Text, lbStartActual.Text, lbStopStandardTimeDate.Text, lbStopStandardTime.Text, lbStopActualDate.Text, lbStopActual.Text, hdfgrid.Value, txtBL.Text, txtDraftSurvey.Text, txtManifest.Text, txtTruckScale.Text, gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                    condition = False
                    Exit For
                Else
                    Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
                    For m As Integer = 0 To Grid.Rows.Count - 1
                        If (clsFc.InsertLoad_Unload_Product_BulkValue(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), Grid.DataKeys(m).Values("_Date"), Grid.DataKeys(m).Values("_DateSort"), Grid.DataKeys(m).Values("_Time"), Grid.DataKeys(m).Values("_STruck"), Grid.DataKeys(m).Values("_Truck6"), Grid.DataKeys(m).Values("_Truck810"), Grid.DataKeys(m).Values("_Trailer"), Grid.DataKeys(m).Values("_Trailer2"), Grid.DataKeys(m).Values("_M"), Grid.DataKeys(m).Values("_P"), Grid.DataKeys(m).Values("_B"), Grid.DataKeys(m).Values("_T"), Grid.DataKeys(m).Values("_C"), Grid.DataKeys(m).Values("_L"), Grid.DataKeys(m).Values("_R"), Grid.DataKeys(m).Values("_Remark"), Grid.DataKeys(m).Values("_Date2"), Grid.DataKeys(m).Values("_Time2"), gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next
                End If
            Next

            Dim dtDelay As DataTable = Session("Delay")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Delay(ViewState("EditBooking"), dr.Item("Date_From"), dr.Item("Date_To"), dr.Item("Time_From"), dr.Item("Time_To"), dr.Item("Cause_Delay"), dr.Item("Delay_Time"), dr.Item("Cause_Code"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            dtDelay = Session("Remark")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Remark(ViewState("EditBooking"), dr.Item("Remark"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            If (clsFc.InsertLoad_Unload_Addition(ViewState("EditBooking"), "", "", "", "", txtWater.Text, "", "", "", "", "", "", "", txtElectricity.Text, txtHopper.Text, txtHopperFrom.Text, txtHopperTo.Text, txtHopperDateFrom.Text, txtHopperDateTo.Text, conn, tran) < 1) Then
                condition = False
            End If
        Else
            condition = False
        End If

        'If (clsFc.UPDATELoad_Unload_Vessel_Status(ViewState("EditBooking"), "C", conn, tran) < 1) Then
        '    condition = False
        'End If
        If (clsFc.InsertAction_Operation(A_Code, ViewState("EditBooking"), "Check Data By", DateTime.Now.ToString("dd MMMM yyyy", New CultureInfo("en-US")), DateTime.Now.ToString("HH:mm"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), "", conn, tran) < 1) Then
            condition = False
        End If
        If (condition) Then
            clsDB.CommitTran(tran)
            LoadBOoking()
            ViewState("Load") = "Not"
            Timer1_Tick(sender, e)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกการตรวจสอบข้อมูลสำเร็จ');", True)
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub btnApprove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApprove.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim User_Modify As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        Dim dtLogSheet As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
        Application.Lock()
        conn.Open()
        Dim A_Code As String = clsDB.GeneratorID(conn, "Action_Operation")
        tran = clsDB.BeginTran(conn)

        clsFc.DeleteLoad_Unload_All(ViewState("EditBooking"), conn, tran)
        If (clsFc.InsertLoad_Unload_Vessel_Bulk(ViewState("EditBooking"), txtThirdParty.Text, txtDepartActualDate.Text, txtDepartAutualTime.Text, lbTugBefore.Text, lbTugAfter.Text, ddlWharfIn.SelectedValue, txtFenderIn.Text, txtCompany.Text, txtEmployeeIn.Text, txtFOR.Text, txtAFT.Text, txtInitialCompany.Text, txtInitialDateFrom.Text, txtInitialDateTo.Text, txtInitialStart.Text, txtInitialEnd.Text, txtFOR_Out.Text, txtAFT_Out.Text, txtFinalCompany.Text, txtFinalDateFrom.Text, txtFinalDateTo.Text, txtFinalStart.Text, txtFinalEnd.Text, ddlWharfOut.SelectedValue, txtFenderOut.Text, txtEmployeeOut.Text, txtNORTender.Text, txtNORTenderTime.Text, "A", conn, tran) > 0) Then
            For i As Integer = 0 To gridProduct.Rows.Count - 1
                Dim txtBL As TextBox = CType(gridProduct.Rows(i).FindControl("txtBL"), TextBox)
                Dim txtDraftSurvey As TextBox = CType(gridProduct.Rows(i).FindControl("txtDraftSurvey"), TextBox)
                Dim txtManifest As TextBox = CType(gridProduct.Rows(i).FindControl("txtManifest"), TextBox)
                Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)

                Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
                Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)
                Dim lbStartActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartActualDate"), Label)
                Dim lbStartActual As Label = CType(gridProduct.Rows(i).FindControl("lbStartActual"), Label)
                Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
                Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
                Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
                Dim lbStopActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopActualDate"), Label)
                Dim lbStopActual As Label = CType(gridProduct.Rows(i).FindControl("lbStopActual"), Label)

                If (clsFc.InsertLoad_Unload_Product_Bulk(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), lbStartStandardTimeDate.Text, lbStartStandardTime.Text, lbStartActualDate.Text, lbStartActual.Text, lbStopStandardTimeDate.Text, lbStopStandardTime.Text, lbStopActualDate.Text, lbStopActual.Text, hdfgrid.Value, txtBL.Text, txtDraftSurvey.Text, txtManifest.Text, txtTruckScale.Text, gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                    condition = False
                    Exit For
                Else
                    Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
                    For m As Integer = 0 To Grid.Rows.Count - 1
                        If (clsFc.InsertLoad_Unload_Product_BulkValue(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), Grid.DataKeys(m).Values("_Date"), Grid.DataKeys(m).Values("_DateSort"), Grid.DataKeys(m).Values("_Time"), Grid.DataKeys(m).Values("_STruck"), Grid.DataKeys(m).Values("_Truck6"), Grid.DataKeys(m).Values("_Truck810"), Grid.DataKeys(m).Values("_Trailer"), Grid.DataKeys(m).Values("_Trailer2"), Grid.DataKeys(m).Values("_M"), Grid.DataKeys(m).Values("_P"), Grid.DataKeys(m).Values("_B"), Grid.DataKeys(m).Values("_T"), Grid.DataKeys(m).Values("_C"), Grid.DataKeys(m).Values("_L"), Grid.DataKeys(m).Values("_R"), Grid.DataKeys(m).Values("_Remark"), Grid.DataKeys(m).Values("_Date2"), Grid.DataKeys(m).Values("_Time2"), gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next
                End If
            Next

            Dim dtDelay As DataTable = Session("Delay")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Delay(ViewState("EditBooking"), dr.Item("Date_From"), dr.Item("Date_To"), dr.Item("Time_From"), dr.Item("Time_To"), dr.Item("Cause_Delay"), dr.Item("Delay_Time"), dr.Item("Cause_Code"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            dtDelay = Session("Remark")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Remark(ViewState("EditBooking"), dr.Item("Remark"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            If (clsFc.InsertLoad_Unload_Addition(ViewState("EditBooking"), "", "", "", "", txtWater.Text, "", "", "", "", "", "", "", txtElectricity.Text, txtHopper.Text, txtHopperFrom.Text, txtHopperTo.Text, txtHopperDateFrom.Text, txtHopperDateTo.Text, conn, tran) < 1) Then
                condition = False
            End If
        Else
            condition = False
        End If

        'If (clsFc.UPDATELoad_Unload_Vessel_Status(ViewState("EditBooking"), "A", conn, tran) < 1) Then
        '    condition = False
        'End If
        If (clsFc.InsertAction_Operation(A_Code, ViewState("EditBooking"), "Approve Data By", DateTime.Now.ToString("dd MMMM yyyy", New CultureInfo("en-US")), DateTime.Now.ToString("HH:mm"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), "", conn, tran) < 1) Then
            condition = False
        End If
        If dtLogSheet.Rows.Count > 0 Then
            If (dtLogSheet.Rows(0).Item("Status") & "" = "A") Then
                If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "OA", conn, tran) < 1) Then
                    condition = False
                End If
            End If
        End If
        If (condition) Then
            clsDB.CommitTran(tran)
            Dim SEND As String = ""
            Dim str As String = ""
            Dim dtBOoking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
            If dtLogSheet.Rows.Count > 0 Then
                Dim dtLogSheetIn As DataTable = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
                Dim Berth As String = ""
                Dim Depart As String = dtLogSheet.Rows(0).Item("Last_Date") & " " & dtLogSheet.Rows(0).Item("Last_Time")
                If (dtLogSheetIn.Rows.Count > 0) Then
                    Berth = dtLogSheetIn.Rows(0).Item("Berthing_Date") & " " & dtLogSheetIn.Rows(0).Item("Berthing_TimeTo")
                End If
                Dim dtLoad As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), "")
                Dim Dis_Date As String = ""
                Dim Dis_Time As String = ""
                Dim Con_Date As String = ""
                Dim Con_Time As String = ""
                For Each dl As DataRow In dtLoad.Rows
                    Try
                        If (Dis_Date = "") Then
                            Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                            Dis_Time = dl.Item("LU_Disconnect_To") & ""
                        End If
                        Dim _DD As String = Dis_Date.Substring(0, 2) & " " & GetNameMonth(Dis_Date.Substring(3, 2)) & " " & CInt("20" & Dis_Date.Substring(6, 2))
                        Dim _D2 As String = dl.Item("LU_Disconnect_Date").Substring(0, 2) & " " & GetNameMonth(dl.Item("LU_Disconnect_Date").Substring(3, 2)) & " " & CInt("20" & dl.Item("LU_Disconnect_Date").Substring(6, 2))
                        If (CDate(ClassFunctionGetData.CDateT(_DD)) < CDate(ClassFunctionGetData.CDateT(_D2))) Then
                            Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                            Dis_Time = dl.Item("LU_Disconnect_To") & ""
                        ElseIf (CDate(ClassFunctionGetData.CDateT(_DD)) = CDate(ClassFunctionGetData.CDateT(_D2))) Then
                            If (CInt(Dis_Time.Split(":")(0)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                            ElseIf (CInt(Dis_Time.Split(":")(0)) = CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                Try
                                    If (CInt(Dis_Time.Split(":")(1)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(1))) Then
                                        Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                        Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                    End If
                                Catch ex As Exception

                                End Try
                            End If
                        End If

                        If (Con_Date = "") Then
                            Con_Date = dl.Item("LU_Connect_Date") & ""
                            Con_Time = dl.Item("LU_Connect_To") & ""
                        End If
                        _DD = Con_Date.Substring(0, 2) & " " & GetNameMonth(Con_Date.Substring(3, 2)) & " " & CInt("20" & Con_Date.Substring(6, 2))
                        _D2 = dl.Item("LU_Connect_Date").Substring(0, 2) & " " & GetNameMonth(dl.Item("LU_Connect_Date").Substring(3, 2)) & " " & CInt("20" & dl.Item("LU_Connect_Date").Substring(6, 2))
                        If (CDate(ClassFunctionGetData.CDateT(_DD)) < CDate(ClassFunctionGetData.CDateT(_D2))) Then
                            Con_Date = dl.Item("LU_Connect_Date") & ""
                            Con_Time = dl.Item("LU_Connect_To") & ""
                        ElseIf (CDate(ClassFunctionGetData.CDateT(_DD)) = CDate(ClassFunctionGetData.CDateT(_D2))) Then
                            If (CInt(Con_Time.Split(":")(0)) < CInt(dl.Item("LU_Connect_To").ToString.Split(":")(0))) Then
                                Con_Date = dl.Item("LU_Connect_Date") & ""
                                Con_Time = dl.Item("LU_Connect_To") & ""
                            ElseIf (CInt(Con_Time.Split(":")(0)) = CInt(dl.Item("LU_Connect_To").ToString.Split(":")(0))) Then
                                Try
                                    If (CInt(Con_Time.Split(":")(1)) < CInt(dl.Item("LU_Connect_To").ToString.Split(":")(1))) Then
                                        Con_Date = dl.Item("LU_Connect_Date") & ""
                                        Con_Time = dl.Item("LU_Connect_To") & ""
                                    End If
                                Catch ex As Exception

                                End Try
                            End If
                        End If
                    Catch ex As Exception

                    End Try

                Next

                If (dtLogSheet.Rows(0).Item("Status") & "" = "A") Then
                    'OA
                    SEND = "MARKETING"
                    str = GenBody("ดำเนินขนถ่ายสินค้าเสร็จสมบูรณ์ และ เรือออกจากท่าเรือแล้ว รอการคำนวณค่าใช้บริการจากระบบ iPORT", ViewState("EditBooking"), dtBOoking.Rows(0).Item("MAgent_no") & "-" & dtBOoking.Rows(0).Item("MAgent_name"), dtBOoking.Rows(0).Item("Vehicle_no") & "-" & dtBOoking.Rows(0).Item("Vehicle_Text"), dtBOoking.Rows(0).Item("Date_From") & "-" & dtBOoking.Rows(0).Item("Date_To"), Berth, Con_Date & " " & Con_Time, Dis_Date & " " & Dis_Time, Depart)
                Else
                    SEND = "PTO"
                    str = GenBody("ดำเนินขนถ่ายสินค้าเสร็จสมบูรณ์", ViewState("EditBooking"), dtBOoking.Rows(0).Item("MAgent_no") & "-" & dtBOoking.Rows(0).Item("MAgent_name"), dtBOoking.Rows(0).Item("Vehicle_no") & "-" & dtBOoking.Rows(0).Item("Vehicle_Text"), dtBOoking.Rows(0).Item("Date_From") & "-" & dtBOoking.Rows(0).Item("Date_To"), Berth, Con_Date & " " & Con_Time, Dis_Date & " " & Dis_Time, Depart)
                End If
            End If
            LoadBOoking()
            ViewState("Load") = "Not"
            Timer1_Tick(sender, e)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกการอนุมัติบข้อมูลสำเร็จ');", True)
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim User_Modify As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        Application.Lock()
        conn.Open()
        Dim A_Code As String = clsDB.GeneratorID(conn, "Action_Operation")
        tran = clsDB.BeginTran(conn)
        Dim start As String = ""
        clsFc.DeleteLoad_Unload_All(ViewState("EditBooking"), conn, tran)
        If (clsFc.InsertLoad_Unload_Vessel_Bulk(ViewState("EditBooking"), txtThirdParty.Text, txtDepartActualDate.Text, txtDepartAutualTime.Text, lbTugBefore.Text, lbTugAfter.Text, ddlWharfIn.SelectedValue, txtFenderIn.Text, txtCompany.Text, txtEmployeeIn.Text, txtFOR.Text, txtAFT.Text, txtInitialCompany.Text, txtInitialDateFrom.Text, txtInitialDateTo.Text, txtInitialStart.Text, txtInitialEnd.Text, txtFOR_Out.Text, txtAFT_Out.Text, txtFinalCompany.Text, txtFinalDateFrom.Text, txtFinalDateTo.Text, txtFinalStart.Text, txtFinalEnd.Text, ddlWharfOut.SelectedValue, txtFenderOut.Text, txtEmployeeOut.Text, txtNORTender.Text, txtNORTenderTime.Text, "S", conn, tran) > 0) Then
            For i As Integer = 0 To gridProduct.Rows.Count - 1
                Dim txtBL As TextBox = CType(gridProduct.Rows(i).FindControl("txtBL"), TextBox)
                Dim txtDraftSurvey As TextBox = CType(gridProduct.Rows(i).FindControl("txtDraftSurvey"), TextBox)
                Dim txtManifest As TextBox = CType(gridProduct.Rows(i).FindControl("txtManifest"), TextBox)
                Dim txtTruckScale As TextBox = CType(gridProduct.Rows(i).FindControl("txtTruckScale"), TextBox)

                Dim lbStartStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTimeDate"), Label)
                Dim lbStartStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStartStandardTime"), Label)
                Dim lbStartActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStartActualDate"), Label)
                Dim lbStartActual As Label = CType(gridProduct.Rows(i).FindControl("lbStartActual"), Label)
                Dim hdfgrid As System.Web.UI.HtmlControls.HtmlInputHidden = CType(gridProduct.Rows(i).FindControl("hdfgrid"), System.Web.UI.HtmlControls.HtmlInputHidden)
                Dim lbStopStandardTimeDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTimeDate"), Label)
                Dim lbStopStandardTime As Label = CType(gridProduct.Rows(i).FindControl("lbStopStandardTime"), Label)
                Dim lbStopActualDate As Label = CType(gridProduct.Rows(i).FindControl("lbStopActualDate"), Label)
                Dim lbStopActual As Label = CType(gridProduct.Rows(i).FindControl("lbStopActual"), Label)
                If (start = "") Then
                    Try
                        start = lbStartActualDate.Text
                        start = start.Substring(0, 2) & " " & GetNameMonth(start.Substring(3, 2)) & " " & CInt("20" & start.Substring(6, 2))
                        start &= " " & lbStartActual.Text
                    Catch ex As Exception

                    End Try

                End If
                If (clsFc.InsertLoad_Unload_Product_Bulk(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), lbStartStandardTimeDate.Text, lbStartStandardTime.Text, lbStartActualDate.Text, lbStartActual.Text, lbStopStandardTimeDate.Text, lbStopStandardTime.Text, lbStopActualDate.Text, lbStopActual.Text, hdfgrid.Value, txtBL.Text, txtDraftSurvey.Text, txtManifest.Text, txtTruckScale.Text, gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                    condition = False
                    Exit For
                Else
                    Dim Grid As GridView = CType(gridProduct.Rows(i).FindControl("gridTransfer"), GridView)
                    For m As Integer = 0 To Grid.Rows.Count - 1
                        If (clsFc.InsertLoad_Unload_Product_BulkValue(ViewState("EditBooking"), gridProduct.DataKeys(i).Values("Product_no"), Grid.DataKeys(m).Values("_Date"), Grid.DataKeys(m).Values("_DateSort"), Grid.DataKeys(m).Values("_Time"), Grid.DataKeys(m).Values("_STruck"), Grid.DataKeys(m).Values("_Truck6"), Grid.DataKeys(m).Values("_Truck810"), Grid.DataKeys(m).Values("_Trailer"), Grid.DataKeys(m).Values("_Trailer2"), Grid.DataKeys(m).Values("_M"), Grid.DataKeys(m).Values("_P"), Grid.DataKeys(m).Values("_B"), Grid.DataKeys(m).Values("_T"), Grid.DataKeys(m).Values("_C"), Grid.DataKeys(m).Values("_L"), Grid.DataKeys(m).Values("_R"), Grid.DataKeys(m).Values("_Remark"), Grid.DataKeys(m).Values("_Date2"), Grid.DataKeys(m).Values("_Time2"), gridProduct.DataKeys(i).Values("BP_Code") & "", conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next
                End If
            Next

            Dim dtDelay As DataTable = Session("Delay")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Delay(ViewState("EditBooking"), dr.Item("Date_From"), dr.Item("Date_To"), dr.Item("Time_From"), dr.Item("Time_To"), dr.Item("Cause_Delay"), dr.Item("Delay_Time"), dr.Item("Cause_Code"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            dtDelay = Session("Remark")
            For Each dr As DataRow In dtDelay.Rows
                If (clsFc.InsertLoad_Unload_Remark(ViewState("EditBooking"), dr.Item("Remark"), conn, tran) < 1) Then
                    condition = False
                    Exit For
                End If
            Next
            If (clsFc.InsertLoad_Unload_Addition(ViewState("EditBooking"), "", "", "", "", txtWater.Text, "", "", "", "", "", "", "", txtElectricity.Text, txtHopper.Text, txtHopperFrom.Text, txtHopperTo.Text, txtHopperDateFrom.Text, txtHopperDateTo.Text, conn, tran) < 1) Then
                condition = False
            End If
        Else
            condition = False
        End If


        'If (clsFc.UPDATELoad_Unload_Vessel_Status(ViewState("EditBooking"), "S", conn, tran) < 1) Then
        '    condition = False
        'End If
        If (clsFc.InsertAction_Operation(A_Code, ViewState("EditBooking"), "Input Data By", DateTime.Now.ToString("dd MMMM yyyy", New CultureInfo("en-US")), DateTime.Now.ToString("HH:mm"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), "", conn, tran) < 1) Then
            condition = False
        End If



        If (condition) Then
            clsDB.CommitTran(tran)
            LoadBOoking()
            ViewState("Load") = "Not"
            Timer1_Tick(sender, e)
            If Not CBool(ViewState("Start")) Then
                Dim str As String = ""
                Dim dtBOoking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
                Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
                Dim Berth As String = ""
                If (dtLogIn.Rows.Count > 0) Then
                    Try
                        Berth = dtLogIn.Rows(0).Item("Berthing_Date") & " " & dtLogIn.Rows(0).Item("Berthing_TimeTo")
                    Catch ex As Exception

                    End Try

                End If
                str = GenBody("เริ่มดำเนินการขนถ่าย", ViewState("EditBooking"), dtBOoking.Rows(0).Item("MAgent_no") & "-" & dtBOoking.Rows(0).Item("MAgent_name"), dtBOoking.Rows(0).Item("Vehicle_no") & "-" & dtBOoking.Rows(0).Item("Vehicle_Text"), dtBOoking.Rows(0).Item("Date_From") & "-" & dtBOoking.Rows(0).Item("Date_To"), Berth, start, "", "")
                SendMail(ViewState("EditBooking"), "CUSTOMER", str)
                ViewState("Start") = True
            End If
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกข้อมูลสำเร็จ');", True)
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub btnReject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReject.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_CancelPopup').src = '../FormPopup/Cancel_popup.aspx?Type=REJECT';", True)
        ModalPopupExtender7.Show()
    End Sub

    Private Sub btnRejectOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRejectOK.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim User_Modify As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name")
        Application.Lock()
        conn.Open()
        Dim A_Code As String = clsDB.GeneratorID(conn, "Action_Operation")
        tran = clsDB.BeginTran(conn)

        If (clsFc.UPDATELoad_Unload_Vessel_Status(ViewState("EditBooking"), "R", conn, tran) < 1) Then
            condition = False
        End If
        If (clsFc.InsertAction_Operation(A_Code, ViewState("EditBooking"), "Reject Data By", DateTime.Now.ToString("dd MMMM yyyy", New CultureInfo("en-US")), DateTime.Now.ToString("HH:mm"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), Session("Cancel_Description") & "", conn, tran) < 1) Then
            condition = False
        End If
        If (condition) Then
            clsDB.CommitTran(tran)
            Session("Cancel_Description") = Nothing
            LoadBOoking()
            ViewState("Load") = "Not"
            Timer1_Tick(sender, e)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('บันทึกข้อมูลสำเร็จ');", True)
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()

    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Sub btnSearchVPS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchVPS.Click
        LoadBOoking()
        ViewState("Load") = "Not"
        Timer1_Tick(sender, e)
    End Sub

    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim service As New _ReportingService.Report

        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        Dim Orientation As Boolean = True
        Dim ReportName As String = String.Empty
        Dim reportDataSource As String = String.Empty
        Dim paraName As String = String.Empty
        Dim paraValue As String = String.Empty
        Dim reportType As String = String.Empty
        Dim urlDisplay As String = String.Empty
        Dim Commend As String = ""
        Dim Complete As String = ""
        Dim Ots_ID As String = String.Empty
        Dim dsReport As New DataSet
        Dim dt As DataTable = Create()
        Dim _L As Integer = 14
        Dim _X As Integer = 5
        Dim dtDelay As DataTable = clsGet.Get_Load_Unload_Delay(ViewState("EditBooking"))
        Dim dtRemark As DataTable = clsGet.Get_Load_Unload_Remark(ViewState("EditBooking"))
        Dim dtOther As DataTable = clsGet.Get_OtherServiceForReportBulk(ViewState("EditBooking"))
        Dim dtProduct As DataTable = clsGet.Get_Booking_ProductOperationBulk(ViewState("EditBooking"))

        Dim TimePort As String = ""
        Dim UnBerth As String = ""
        Try
            If (CDbl(ViewState("BunkerFO_Point")) > 0) Then
                Dim dr As DataRow = dtProduct.NewRow()
                dr.Item("Product_no") = "Bunker FO"
                dr.Item("Group_no") = "Bunker"
                dr.Item("Product_Event") = "L"
                dr.Item("Product_Amount") = ViewState("BunkerFO_Point")
                dr.Item("Product_name") = "Bunker FO"
                dtProduct.Rows.Add(dr)
                dtProduct.AcceptChanges()
            End If
        Catch ex As Exception

        End Try
        Try
            If (CDbl(ViewState("BunkerDO_Point")) > 0) Then
                Dim dr As DataRow = dtProduct.NewRow()
                dr.Item("Product_no") = "Bunker DO"
                dr.Item("Group_no") = "Bunker"
                dr.Item("Product_Event") = "L"
                dr.Item("Product_Amount") = ViewState("BunkerDO_Point")
                dr.Item("Product_name") = "Bunker DO"
                dtProduct.Rows.Add(dr)
                dtProduct.AcceptChanges()
            End If
        Catch ex As Exception

        End Try

        If (dtDelay.Rows.Count > _L) Then
            _L = dtDelay.Rows.Count
        End If
        If (dtRemark.Rows.Count > _L) Then
            _L = dtRemark.Rows.Count
        End If
        If (dtOther.Rows.Count > _L) Then
            _L = dtOther.Rows.Count
        End If
        Dim countrow As Integer = 0
        For Each dr As DataRow In dtProduct.Rows
            Dim Temp As DataTable = clsGet.Get_Load_Unload_Product_Bulk(ViewState("EditBooking"), dr.Item("Product_no"), dr.Item("BP_Code"))
            If (Temp.Rows.Count > 0) Then
                If (Temp.Rows.Count > 14) Then
                    countrow += Temp.Rows.Count
                Else
                    countrow += 14
                End If
            End If

        Next
        If (_L < countrow) Then
            _L = countrow
        End If
        Dim OtsOld As String = ""
        For i As Integer = 1 To _L
            Dim dr As DataRow = dt.NewRow()
            Select Case (i)
                Case 1
                    dr.Item("H_Code") = 1
                    dr.Item("H_Description") = "Vessel Arrived"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = lbarrived.Text
                Case 2
                    dr.Item("H_Code") = 2
                    dr.Item("H_Description") = "Estimate NOR"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = lbNOR.Text
                Case 3
                    dr.Item("H_Code") = 3
                    dr.Item("H_Description") = "POB"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = lbPOB.Text
                Case 4
                    dr.Item("H_Code") = 4
                    dr.Item("H_Description") = "NOR Tender"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = txtNORTender.Text & txtNORTenderTime.Text
                Case 5
                    dr.Item("H_Code") = 5
                    dr.Item("H_Description") = "NOR accepted"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = lbAccept.Text
                Case 6
                    dr.Item("H_Code") = 6
                    dr.Item("H_Description") = "First Line"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = lbFirstling.Text
                Case 7
                    dr.Item("H_Code") = 7
                    Try
                        If (CInt(ddlWharfIn.Text)) Then
                            dr.Item("H_Standard") = " Wharf :" & clsGet.Get_WharfName(ddlWharfIn.Text) & " Fender " & txtFenderIn.Text
                        End If
                    Catch ex As Exception
                        dr.Item("H_Standard") = " Wharf :" & ddlWharfIn.Text & " Fender " & txtFenderIn.Text
                    End Try
                    dr.Item("H_Description") = "Berthed"

                    dr.Item("H_Actual") = lbBerthedDate.Text & " " & lbBerthed.Text
                Case 8
                    dr.Item("H_Code") = 8
                    dr.Item("H_Description") = "Initial Draft Survey        F=" & txtFOR.Text & " M A=" & txtAFT.Text & " M"
                    dr.Item("H_Standard") = txtInitialCompany.Text
                    dr.Item("H_Actual") = txtInitialDateFrom.Text & " " & txtInitialStart.Text & " - " & txtInitialDateTo.Text & " " & txtInitialEnd.Text
                Case 9
                    dr.Item("H_Code") = 9
                    dr.Item("H_Description") = "Commend"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = ""
                Case 10
                    dr.Item("H_Code") = 10
                    dr.Item("H_Description") = "Completed"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = ""
                Case 11
                    dr.Item("H_Code") = 11
                    dr.Item("H_Description") = "Final Draft Survey        F=" & txtFOR_Out.Text & " M A=" & txtAFT_Out.Text & " M"
                    dr.Item("H_Standard") = txtInitialCompany.Text
                    dr.Item("H_Actual") = txtFinalDateFrom.Text & " " & txtFinalStart.Text & " - " & txtFinalDateTo.Text & " " & txtFinalEnd.Text
                Case 12
                    dr.Item("H_Code") = 12
                    dr.Item("H_Description") = "Ship From the Port"
                    Try
                        If (CInt(ddlWharfOut.Text)) Then
                            dr.Item("H_Standard") = " Wharf :" & clsGet.Get_WharfName(ddlWharfOut.Text) & " Fender " & txtFenderOut.Text
                        End If
                    Catch ex As Exception
                        dr.Item("H_Standard") = " Wharf :" & ddlWharfOut.Text & " Fender " & txtFenderOut.Text
                    End Try
                    dr.Item("H_Actual") = txtInitialDateFrom.Text & " " & txtInitialStart.Text & " - " & txtInitialDateTo.Text & " " & txtInitialEnd.Text
                Case 13
                    dr.Item("H_Code") = 13
                    dr.Item("H_Description") = "Departed"
                    dr.Item("H_Standard") = ""
                    dr.Item("H_Actual") = txtDepartActualDate.Text & " " & txtDepartAutualTime.Text
                Case 14
                    dr.Item("H_Code") = 14
                    dr.Item("H_Description") = "Total Ship Time at IRPC PORT"
                    dr.Item("H_Standard") = ""
                    Try
                        'Dim ts = DateDiff("n", lbBerthedDate.Text & " " & lbBerthed.Text, txtDepartActualDate.Text & " " & txtDepartAutualTime.Text)
                        Dim ts = DateDiff("n", lbFirstling.Text, txtDepartActualDate.Text & " " & txtDepartAutualTime.Text)
                        Dim Day As Integer = 0
                        Dim Hour As Integer = 0
                        Dim Minute As Integer = 0
                        Day = ts \ 1440
                        ts = ts Mod 1440
                        Hour = ts \ 60
                        ts = ts Mod 60
                        Minute = ts

                        TimePort = Day & " Day " & Hour & " Hour " & Minute & " Minute"
                    Catch ex As Exception

                    End Try
                    dr.Item("H_Actual") = TimePort
                Case Else
                    dr.Item("H_Code") = 14
                    dr.Item("H_Description") = "Total Ship Time at IRPC PORT"
                    dr.Item("H_Standard") = ""
                    Try
                        'Dim ts = DateDiff("n", lbBerthedDate.Text & " " & lbBerthed.Text, txtDepartActualDate.Text & " " & txtDepartAutualTime.Text)
                        Dim ts = DateDiff("n", lbFirstling.Text, txtDepartActualDate.Text & " " & txtDepartAutualTime.Text)
                        Dim Day As Integer = 0
                        Dim Hour As Integer = 0
                        Dim Minute As Integer = 0
                        Day = ts \ 1440
                        ts = ts Mod 1440
                        Hour = ts \ 60
                        ts = ts Mod 60
                        Minute = ts

                        TimePort = Day & " Day " & Hour & " Hour " & Minute & " Minute"
                    Catch ex As Exception

                    End Try
                    dr.Item("H_Actual") = TimePort
            End Select
            If (dtDelay.Rows.Count > 0) Then
                If (i < dtDelay.Rows.Count) Then
                    dr.Item("D_Code") = i - 1
                    dr.Item("D_Time") = dtDelay.Rows(i - 1).Item("Delay_DateTime")
                    dr.Item("D_Cause") = dtDelay.Rows(i - 1).Item("Cause_Delay")
                    dr.Item("D_Delay") = dtDelay.Rows(i - 1).Item("Delay_Time")
                Else
                    dr.Item("D_Code") = dtDelay.Rows.Count - 1
                    dr.Item("D_Time") = dtDelay.Rows(dtDelay.Rows.Count - 1).Item("Delay_DateTime")
                    dr.Item("D_Cause") = dtDelay.Rows(dtDelay.Rows.Count - 1).Item("Cause_Delay")
                    dr.Item("D_Delay") = dtDelay.Rows(dtDelay.Rows.Count - 1).Item("Delay_Time")
                End If
            Else
                dr.Item("D_Code") = ""
                dr.Item("D_Time") = ""
                dr.Item("D_Cause") = ""
                dr.Item("D_Delay") = ""
            End If
            If (dtRemark.Rows.Count > 0) Then
                If (i < dtRemark.Rows.Count) Then
                    dr.Item("R_Code") = i - 1
                    dr.Item("R_Remark") = dtRemark.Rows(i - 1).Item("Remark")
                Else
                    dr.Item("R_Code") = dtRemark.Rows.Count - 1
                    dr.Item("R_Remark") = dtRemark.Rows(dtRemark.Rows.Count - 1).Item("Remark")
                End If
            Else
                dr.Item("R_Code") = ""
                dr.Item("R_Remark") = ""
            End If
            If (dtOther.Rows.Count > 0) Then
                If (i < dtOther.Rows.Count) Then
                    dr.Item("O_Code") = i - 1
                    dr.Item("O_Name") = dtOther.Rows(i - 1).Item("Text_line")
                    dr.Item("O_Rate") = dtOther.Rows(i - 1).Item("Rate")
                    dr.Item("O_Qty") = dtOther.Rows(i - 1).Item("Amount")
                    dr.Item("O_Amount") = dtOther.Rows(i - 1).Item("Total")
                    If (OtsOld <> dtOther.Rows(i - 1).Item("Ots_ID") & "") Then
                        If (Ots_ID = "") Then
                            Ots_ID = dtOther.Rows(i - 1).Item("Ots_ID")
                        Else
                            Ots_ID &= "," & dtOther.Rows(i - 1).Item("Ots_ID")
                        End If
                    End If
                    OtsOld = dtOther.Rows(i - 1).Item("Ots_ID")
                Else
                    dr.Item("O_Code") = dtOther.Rows.Count - 1
                    dr.Item("O_Name") = dtOther.Rows(dtOther.Rows.Count - 1).Item("Text_line")
                    dr.Item("O_Rate") = dtOther.Rows(dtOther.Rows.Count - 1).Item("Rate")
                    dr.Item("O_Qty") = dtOther.Rows(dtOther.Rows.Count - 1).Item("Amount")
                    dr.Item("O_Amount") = dtOther.Rows(dtOther.Rows.Count - 1).Item("Total")
                    If (OtsOld <> dtOther.Rows(dtOther.Rows.Count - 1).Item("Ots_ID") & "") Then
                        If (Ots_ID = "") Then
                            Ots_ID = dtOther.Rows(dtOther.Rows.Count - 1).Item("Ots_ID")
                        Else
                            Ots_ID &= "," & dtOther.Rows(dtOther.Rows.Count - 1).Item("Ots_ID")
                        End If
                    End If
                    OtsOld = dtOther.Rows(dtOther.Rows.Count - 1).Item("Ots_ID")
                End If
            Else
                dr.Item("O_Code") = ""
                dr.Item("O_Name") = ""
                dr.Item("O_Rate") = ""
                dr.Item("O_Qty") = ""
                dr.Item("O_Amount") = ""
            End If
            

            dt.Rows.Add(dr)
            dt.AcceptChanges()
        Next

        Dim count As Integer = 0
        Dim C_index As Integer = 0
        For Each dp As DataRow In dtProduct.Rows
            Dim dtLoadUN As DataTable
            dtLoadUN = clsGet.Get_Load_Unload_Product_Bulk(ViewState("EditBooking"), dp.Item("Product_no"), dp.Item("BP_Code"))
            If (dtLoadUN.Rows.Count > 0) Then
                C_index += 1
                Dim _B As Double = 0.0
                Dim _T As Double = 0.0
                Dim _LL As Double = 0.0
                Dim _P As Double = 0.0
                Dim _C As Double = 0.0
                Dim _R As Double = 0.0
                Dim looptime As Integer = dtLoadUN.Rows.Count
                If (dtLoadUN.Rows.Count < 14) Then
                    looptime = 14
                End If
                Dim Truck6 As Integer = 0
                Dim Truck810 As Integer = 0
                Dim Trailer As Integer = 0
                Dim Trailer2 As Integer = 0
                Dim S_1 As String = "0"

                Dim S_2 As String = ""

                Dim S_3 As String = "0"
                Dim BL As String = ""
                Dim Manifest As String = ""
                Dim Truckscale As String = ""
                For k As Integer = 0 To looptime - 1
                    Dim V_2 As String = ""
                    Dim V_name2 As String = ""
                    Dim V_3 As String = "0"
                    Dim S_name2 As String = ""

                    Dim V_name3 As String = ""

                    Dim S_name3 As String = ""


                    If (k > dtLoadUN.Rows.Count - 1) Then
                        dt.Rows(count).Item("T_Code") = dtLoadUN.Rows.Count - 1 & dp.Item("BP_Code")
                        dt.Rows(count).Item("T_DFrom") = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_Date")
                        dt.Rows(count).Item("T_DTo") = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_Date2")
                        dt.Rows(count).Item("T_TFrom") = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_Time")
                        dt.Rows(count).Item("T_TTo") = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_Time2")
                        dt.Rows(count).Item("V_1") = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_STruck")
                        dt.Rows(count).Item("S_1") = CInt(S_1)
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_M") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(MT)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_M")
                                S_name2 = "Total Weight(MT)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(MT)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_M")
                                S_name3 = "Total Weight(MT)"
                            End If
                        End If
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_P") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(PACKAGE)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_P")
                                S_name2 = "Total Weight(PACKAGE)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(PACKAGE)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_P")
                                S_name3 = "Total Weight(PACKAGE)"
                            End If
                        End If
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_B") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(BAG)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_B")
                                S_name2 = "Total Weight(BAG)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(BAG)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_B")
                                S_name3 = "Total Weight(BAG)"
                            End If
                        End If
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_T") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(DRUM)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_T")
                                S_name2 = "Total Weight(BAG)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(DRUM)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_T")
                                S_name3 = "Total Weight(DRUM)"
                            End If
                        End If
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_C") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(PCS)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_C")
                                S_name2 = "Total Weight(PCS)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(PCS)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_C")
                                S_name3 = "Total Weight(PCS)"
                            End If
                        End If
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_R") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(ROLL)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_R")
                                S_name2 = "Total Weight(ROLL)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(ROLL)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_R")
                                S_name3 = "Total Weight(ROLL)"
                            End If
                        End If
                        If (dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_L") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(LITER)"
                                V_2 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_L")
                                S_name2 = "Total Weight(LITER)"
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(LITER)"
                                V_3 = dtLoadUN.Rows(dtLoadUN.Rows.Count - 1).Item("_L")
                                S_name3 = "Total Weight(LITER)"
                            End If
                        End If
                    Else
                        dt.Rows(count).Item("T_Code") = k & dp.Item("BP_Code")
                        dt.Rows(count).Item("T_DFrom") = dtLoadUN.Rows(k).Item("_Date")
                        dt.Rows(count).Item("T_DTo") = dtLoadUN.Rows(k).Item("_Date2")
                        dt.Rows(count).Item("T_TFrom") = dtLoadUN.Rows(k).Item("_Time")
                        dt.Rows(count).Item("T_TTo") = dtLoadUN.Rows(k).Item("_Time2")
                        dt.Rows(count).Item("V_1") = dtLoadUN.Rows(k).Item("_STruck")
                        dt.Rows(count).Item("S_1") = CInt(S_1) + CInt(dtLoadUN.Rows(k).Item("_STruck"))
                        S_1 = CInt(S_1) + CInt(dtLoadUN.Rows(k).Item("_STruck"))

                        If (dtLoadUN.Rows(k).Item("_M") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(MT)"
                                V_2 = dtLoadUN.Rows(k).Item("_M")
                                S_name2 = "Total Weight(MT)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_M"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(MT)"
                                V_3 = dtLoadUN.Rows(k).Item("_M")
                                S_name3 = "Total Weight(MT)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_M"))
                            End If
                        End If
                        If (dtLoadUN.Rows(k).Item("_P") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(PACKAGE)"
                                V_2 = dtLoadUN.Rows(k).Item("_P")
                                S_name2 = "Total Weight(PACKAGE)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_P"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(PACKAGE)"
                                V_3 = dtLoadUN.Rows(k).Item("_P")
                                S_name3 = "Total Weight(PACKAGE)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_P"))
                            End If
                        End If
                        If (dtLoadUN.Rows(k).Item("_B") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(BAG)"
                                V_2 = dtLoadUN.Rows(k).Item("_B")
                                S_name2 = "Total Weight(BAG)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_B"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(BAG)"
                                V_3 = dtLoadUN.Rows(k).Item("_B")
                                S_name3 = "Total Weight(BAG)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_B"))
                            End If
                        End If
                        If (dtLoadUN.Rows(k).Item("_T") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(DRUM)"
                                V_2 = dtLoadUN.Rows(k).Item("_T")
                                S_name2 = "Total Weight(DRUM)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_T"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(DRUM)"
                                V_3 = dtLoadUN.Rows(k).Item("_T")
                                S_name3 = "Total Weight(DRUM)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_T"))
                            End If
                        End If
                        If (dtLoadUN.Rows(k).Item("_C") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(PCS)"
                                V_2 = dtLoadUN.Rows(k).Item("_C")
                                S_name2 = "Total Weight(PCS)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_C"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(PCS)"
                                V_3 = dtLoadUN.Rows(k).Item("_C")
                                S_name3 = "Total Weight(PCS)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_C"))
                            End If
                        End If
                        If (dtLoadUN.Rows(k).Item("_R") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(ROLL)"
                                V_2 = dtLoadUN.Rows(k).Item("_R")
                                S_name2 = "Total Weight(ROLL)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_R"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(ROLL)"
                                V_3 = dtLoadUN.Rows(k).Item("_R")
                                S_name3 = "Total Weight(ROLL)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_R"))
                            End If
                        End If
                        If (dtLoadUN.Rows(k).Item("_L") & "" <> "0") Then
                            If (V_name2 = "") Then
                                V_name2 = "Weight(LITER)"
                                V_2 = dtLoadUN.Rows(k).Item("_L")
                                S_name2 = "Total Weight(LITER)"
                                If (S_2 = "") Then
                                    S_2 = "0"
                                End If
                                S_2 += CDbl(dtLoadUN.Rows(k).Item("_L"))
                            ElseIf (V_name3 = "") Then
                                V_name3 = "Weight(LITER)"
                                V_3 = dtLoadUN.Rows(k).Item("_L")
                                S_name3 = "Total Weight(LITER)"
                                If (S_3 = "") Then
                                    S_3 = "0"
                                End If
                                S_3 += CDbl(dtLoadUN.Rows(k).Item("_L"))
                            End If
                        End If
                        Truck6 += CInt(dtLoadUN.Rows(k).Item("_Truck6"))
                        Truck810 += CInt(dtLoadUN.Rows(k).Item("_Truck810"))
                        Trailer += CInt(dtLoadUN.Rows(k).Item("_Trailer"))
                        Trailer2 += CInt(dtLoadUN.Rows(k).Item("_Trailer2"))
                    End If
                    If (V_2 = "") Then
                        V_2 = "0.00"
                    End If
                    If (V_3 = "") Then
                        V_3 = "0.00"
                    End If
                    If (S_2 = "") Then
                        S_2 = "0.00"
                    End If
                    If (S_3 = "") Then
                        S_3 = "0.00"
                    End If
                    dt.Rows(count).Item("V_Name2") = V_name2
                    dt.Rows(count).Item("V_2") = V_2
                    dt.Rows(count).Item("S_Name2") = S_name2
                    dt.Rows(count).Item("S_2") = S_2
                    dt.Rows(count).Item("V_Name3") = V_name3
                    dt.Rows(count).Item("V_3") = V_3
                    dt.Rows(count).Item("S_Name3") = S_name3
                    dt.Rows(count).Item("S_3") = S_3


                    Dim dtLoadUN2 As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), dp.Item("Product_no"), dp.Item("BP_Code"))
                    If (dtLoadUN2.Rows.Count = 0) Then
                        dtLoadUN2 = clsGet.Get_Load_Unload_Vessel_Product_Detail_Bunker(ViewState("EditBooking"), dp.Item("Product_no"))
                    End If

                    Try
                        dt.Rows(count).Item("B_Code") = C_index & "). " & dtLoadUN2.Rows(0).Item("Product_name")

                    Catch ex As Exception
                        dt.Rows(count).Item("B_Code") = C_index & "). " & dtLoadUN2.Rows(0).Item("Product_no")

                    End Try
                    Dim dtproductTarget As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"))
                    If (dtproductTarget.Rows.Count > 0) Then
                        For Each dps As DataRow In dtproductTarget.Rows
                            Dim chk As Boolean = True
                            If (dps.Item("Product_no") = dp.Item("Product_no")) Then
                                dt.Rows(count).Item("B_Target") = dps.Item("Product_Amount") & " MT"
                                chk = False
                                Exit For
                            End If
                            If (chk) Then
                                dt.Rows(count).Item("B_Target") = "1 MT"
                            End If
                        Next
                    Else
                        dt.Rows(count).Item("B_Target") = "1 MT"
                    End If
                    If (Commend = "") Then
                        If (dtLoadUN2.Rows.Count > 0) Then
                            Commend = dtLoadUN2.Rows(0).Item("LU_StartActual_Date") & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time")
                        Else
                            Commend = ""
                        End If
                    End If
                    If (dtLoadUN2.Rows.Count > 0) Then
                        Complete = dtLoadUN2.Rows(0).Item("LU_StopActual_Date") & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time")
                    Else
                        Complete = ""
                    End If
                    Select Case (k)
                        Case 0
                            dt.Rows(count).Item("B_Description") = "Bill of Landing"
                            dt.Rows(count).Item("B_Standard") = ""
                            Try
                                dt.Rows(count).Item("B_Actual") = FormatNumber(CDbl(dtLoadUN2.Rows(0).Item("BU_Bill")), 3) & " MT"
                            Catch ex As Exception
                                dt.Rows(count).Item("B_Actual") = "- MT"
                            End Try

                            dt.Rows(count).Item("B_SubCode") = 1
                            Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                            dt.Rows(count).Item("F_Actual") = ts
                            BL = dtLoadUN2.Rows(0).Item("BU_Bill") & ""
                            Truckscale = dtLoadUN2.Rows(0).Item("BU_Truck") & ""
                            dt.Rows(count).Item("F_Standard") = Truckscale
                        Case 1
                            dt.Rows(count).Item("B_Description") = "Draft Survey"
                            dt.Rows(count).Item("B_Standard") = ""
                            Try
                                dt.Rows(count).Item("B_Actual") = FormatNumber(CDbl(dtLoadUN2.Rows(0).Item("BU_Draft")), 3) & " MT"
                            Catch ex As Exception
                                dt.Rows(count).Item("B_Actual") = "- MT"
                            End Try

                            dt.Rows(count).Item("B_SubCode") = 2
                            Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                            dt.Rows(count).Item("F_Actual") = ts
                            Truckscale = dtLoadUN2.Rows(0).Item("BU_Truck") & ""
                            dt.Rows(count).Item("F_Standard") = Truckscale
                        Case 2
                            dt.Rows(count).Item("B_Description") = "Manifest"
                            dt.Rows(count).Item("B_Standard") = ""
                            Try
                                dt.Rows(count).Item("B_Actual") = FormatNumber(CDbl(dtLoadUN2.Rows(0).Item("BU_Manifest")), 3) & " MT"
                            Catch ex As Exception
                                dt.Rows(count).Item("B_Actual") = "- MT"
                            End Try

                            dt.Rows(count).Item("B_SubCode") = 3
                            Manifest = dtLoadUN2.Rows(0).Item("BU_Manifest") & ""
                            Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                            dt.Rows(count).Item("F_Actual") = ts
                            Truckscale = dtLoadUN2.Rows(0).Item("BU_Truck") & ""
                            dt.Rows(count).Item("F_Standard") = Truckscale
                        Case 3
                            dt.Rows(count).Item("B_Description") = "Truck Scale"
                            dt.Rows(count).Item("B_Standard") = ""
                            Try
                                dt.Rows(count).Item("B_Actual") = FormatNumber(CDbl(dtLoadUN2.Rows(0).Item("BU_Truck")), 3) & " MT"
                            Catch ex As Exception
                                dt.Rows(count).Item("B_Actual") = "- MT"
                            End Try

                            dt.Rows(count).Item("B_SubCode") = 4
                            Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                            dt.Rows(count).Item("F_Actual") = ts
                            Truckscale = dtLoadUN2.Rows(0).Item("BU_Truck") & ""
                            dt.Rows(count).Item("F_Standard") = Truckscale
                        Case 4
                            If (BL & "" <> "") Then
                                'BL
                                Try
                                    If (CDbl(Truckscale) >= CDbl(BL)) Then
                                        dt.Rows(count).Item("B_Description") = "Gain from BL"
                                        dt.Rows(count).Item("B_Standard") = ""
                                        dt.Rows(count).Item("B_Actual") = (CDbl(Truckscale) - CDbl(BL)).ToString("####################0.000") & " MT. or " & (((CDbl(Truckscale) - CDbl(BL)) / CDbl(BL)) * 100).ToString("##0.00") & "%"
                                        dt.Rows(count).Item("B_SubCode") = 5
                                    Else
                                        dt.Rows(count).Item("B_Description") = "Loss from BL"
                                        dt.Rows(count).Item("B_Standard") = ""
                                        dt.Rows(count).Item("B_Actual") = (CDbl(BL) - CDbl(Truckscale)).ToString("####################0.000") & " MT. or " & (((CDbl(BL) - CDbl(Truckscale)) / CDbl(BL)) * 100).ToString("##0.00") & "%"
                                        dt.Rows(count).Item("B_SubCode") = 5
                                    End If
                                Catch ex As Exception

                                End Try

                            Else
                                'Manifest
                                Try
                                    If (CDbl(Truckscale) >= CDbl(Manifest)) Then
                                        dt.Rows(count).Item("B_Description") = "Gain from Manifest"
                                        dt.Rows(count).Item("B_Standard") = ""
                                        dt.Rows(count).Item("B_Actual") = (CDbl(Truckscale) - CDbl(Manifest)).ToString("####################0.000") & " MT. or " & (((CDbl(Truckscale) - CDbl(Manifest)) / CDbl(Manifest)) * 100).ToString("##0.00") & "%"
                                        dt.Rows(count).Item("B_SubCode") = 5
                                    Else
                                        dt.Rows(count).Item("B_Description") = "Loss from Manifest"
                                        dt.Rows(count).Item("B_Standard") = ""
                                        dt.Rows(count).Item("B_Actual") = (CDbl(Manifest) - CDbl(Truckscale)).ToString("####################0.000") & " MT. or " & (((CDbl(Manifest) - CDbl(Truckscale)) / CDbl(Manifest)) * 100).ToString("##0.00") & "%"
                                        dt.Rows(count).Item("B_SubCode") = 5
                                    End If
                                Catch ex As Exception

                                End Try
                                Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                                dt.Rows(count).Item("F_Actual") = ts
                                dt.Rows(count).Item("F_Standard") = Truckscale
                            End If
                        Case 5
                            dt.Rows(count).Item("B_Description") = "Total time cargo Transfer"
                            dt.Rows(count).Item("B_Standard") = ""

                            dt.Rows(count).Item("B_SubCode") = 6
                            Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                            Dim T As String = ""
                            Try
                                Dim Day As Integer = 0
                                Dim Hour As Integer = 0
                                Dim Minute As Integer = 0
                                Day = ts \ 1440
                                ts = ts Mod 1440
                                Hour = ts \ 60
                                ts = ts Mod 60
                                Minute = ts

                                T = Day & " Day " & Hour & " Hour " & Minute & " Minute"
                            Catch ex As Exception

                            End Try
                            dt.Rows(count).Item("B_Actual") = T

                            dt.Rows(count).Item("F_Actual") = ts
                            Truckscale = dtLoadUN2.Rows(0).Item("BU_Truck") & ""
                            dt.Rows(count).Item("F_Standard") = Truckscale
                        Case Else
                            dt.Rows(count).Item("B_Description") = "Total time cargo Transfer"
                            dt.Rows(count).Item("B_Standard") = ""

                            dt.Rows(count).Item("B_SubCode") = 6
                            Dim ts = DateDiff("n", dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StartActual_Time"), dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " " & "20" & dtLoadUN2.Rows(0).Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dtLoadUN2.Rows(0).Item("LU_StopActual_Time"))
                            Dim T As String = ""
                            Try
                                Dim Day As Integer = 0
                                Dim Hour As Integer = 0
                                Dim Minute As Integer = 0
                                Day = ts \ 1440
                                ts = ts Mod 1440
                                Hour = ts \ 60
                                ts = ts Mod 60
                                Minute = ts

                                T = Day & " Day " & Hour & " Hour " & Minute & " Minute"
                            Catch ex As Exception

                            End Try
                            dt.Rows(count).Item("B_Actual") = T

                            dt.Rows(count).Item("F_Actual") = ts
                            Truckscale = dtLoadUN2.Rows(0).Item("BU_Truck") & ""
                            dt.Rows(count).Item("F_Standard") = Truckscale
                    End Select
                    dt.AcceptChanges()
                    count += 1
                Next
                For Each dx As DataRow In dt.Rows
                    If (dx.Item("B_Code") & "" = C_index & "). " & dp.Item("Product_no")) Or (dx.Item("B_Code") & "" = C_index & "). " & dp.Item("Product_name")) Then
                        dx.Item("Truck6") = Truck6
                        dx.Item("Truck810") = Truck810
                        dx.Item("Trailer") = Trailer
                        dx.Item("Trailer2") = Trailer2
                        dx.Item("SUM") = Truck6 + Truck810 + Trailer + Trailer2
                        dt.AcceptChanges()
                    End If
                Next

            End If
        Next
        dt.Rows(8).Item("H_Actual") = Commend
        dt.Rows(9).Item("H_Actual") = Complete
        Dim Input As String = ""
        Dim Check As String = ""
        Dim Approve As String = ""
        Try
            Dim Temp As String = clsGet.Get_NameInputOperation(lbBooking_no.Text, "00010")
            If (Temp <> "") Then
                Input = Temp.Split("$")(0).ToString & Environment.NewLine & Temp.Split("$")(1).ToString
            End If
        Catch ex As Exception

        End Try
        Try
            Dim Temp As String = clsGet.Get_NameInputOperation(lbBooking_no.Text, "00015")
            If (Temp <> "") Then
                Check = Temp.Split("$")(0).ToString & Environment.NewLine & Temp.Split("$")(1).ToString
            End If
        Catch ex As Exception

        End Try
        Try
            Dim Temp As String = clsGet.Get_NameInputOperation(lbBooking_no.Text, "00016")
            If (Temp <> "") Then
                Approve = Temp.Split("$")(0).ToString & Environment.NewLine & Temp.Split("$")(1).ToString
            End If
        Catch ex As Exception

        End Try
        dsReport.Tables.Add(dt.Copy)
        dsReport.AcceptChanges()
        ReportName = "Ship_Performance_Bulk.rdlc"
        reportDataSource = "Performance_Bulk_Value"
        paraName = "Booking_no;Vessel;Direction;Pilot;staff;Third;Water;Electricity;Hopper;Ots_ID;Tug_Before;Tug_After;TimePort;UnBerth;Input;Check;Approve"
        paraValue = lbBooking_no.Text & ";" & lbVessel.Text & ";" & lbDirection.Text & ";" & lbPilotNo.Text & ";" & txtCompany.Text.Replace(";", "") & " " & txtEmployeeIn.Text.Replace(";", "") & " Person;" & txtThirdParty.Text & ";" & txtWater.Text & ";" & txtElectricity.Text & ";" & txtHopper.Text & "PC " & txtHopperDateFrom.Text & " " & txtHopperFrom.Text & " To " & txtHopperDateTo.Text & " " & txtHopperTo.Text & ";" & Ots_ID & ";" & lbTugBefore.Text & ";" & lbTugAfter.Text & ";" & TimePort & ";" & txtCompany.Text.Replace(";", "") & " " & txtEmployeeOut.Text.Replace(";", "") & " Person;" & Input & ";" & Check & ";" & Approve
        Orientation = True
        reportType = "pdf"

        urlDisplay = service.CreateReporting(dsReport, reportDataSource, reportType, ReportName, paraName, paraValue, Orientation, "")

        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "window.open('" + urlDisplay + "','_blank','" + optWindow + "');", True)

    End Sub


    Private Function Create() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("H_Code", GetType(String))
        dt.Columns.Add("H_Description", GetType(String))
        dt.Columns.Add("H_Standard", GetType(String))
        dt.Columns.Add("H_Actual", GetType(String))
        dt.Columns.Add("B_Code", GetType(String))
        dt.Columns.Add("B_Target", GetType(String))
        dt.Columns.Add("T_Code", GetType(String))
        dt.Columns.Add("T_DFrom", GetType(String))
        dt.Columns.Add("T_DTo", GetType(String))
        dt.Columns.Add("T_TFrom", GetType(String))
        dt.Columns.Add("T_TTo", GetType(String))
        dt.Columns.Add("V_1", GetType(String))
        dt.Columns.Add("S_1", GetType(String))
        dt.Columns.Add("V_Name2", GetType(String))
        dt.Columns.Add("V_2", GetType(String))
        dt.Columns.Add("S_Name2", GetType(String))
        dt.Columns.Add("S_2", GetType(String))
        dt.Columns.Add("V_Name3", GetType(String))
        dt.Columns.Add("V_3", GetType(String))
        dt.Columns.Add("S_Name3", GetType(String))
        dt.Columns.Add("S_3", GetType(String))
        dt.Columns.Add("Truck6", GetType(String))
        dt.Columns.Add("Truck810", GetType(String))
        dt.Columns.Add("Trailer", GetType(String))
        dt.Columns.Add("Trailer2", GetType(String))
        dt.Columns.Add("SUM", GetType(String))
        dt.Columns.Add("B_Description", GetType(String))
        dt.Columns.Add("B_Standard", GetType(String))
        dt.Columns.Add("B_Actual", GetType(String))
        dt.Columns.Add("F_Code", GetType(String))
        dt.Columns.Add("F_Description", GetType(String))
        dt.Columns.Add("F_Standard", GetType(String))
        dt.Columns.Add("F_Actual", GetType(String))
        dt.Columns.Add("D_Code", GetType(String))
        dt.Columns.Add("D_Time", GetType(String))
        dt.Columns.Add("D_Cause", GetType(String))
        dt.Columns.Add("D_Delay", GetType(String))
        dt.Columns.Add("R_Code", GetType(String))
        dt.Columns.Add("R_Remark", GetType(String))
        dt.Columns.Add("O_Code", GetType(String))
        dt.Columns.Add("O_Name", GetType(String))
        dt.Columns.Add("O_Rate", GetType(String))
        dt.Columns.Add("O_Qty", GetType(String))
        dt.Columns.Add("O_Amount", GetType(String))
        dt.Columns.Add("B_SubCode", GetType(String))
        dt.AcceptChanges()

        Return dt
    End Function

    Private Function GenBody(ByVal str As String, ByVal booking_no As String, ByVal Agent As String, ByVal Vessel As String, ByVal Laycan As String, ByVal Berth As String, ByVal Start As String, ByVal _Stop As String, ByVal Depart As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='left'><font class='White-Style' font-weight:bold style='color:#000000'>" & str & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"

        HTML &= "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & booking_no & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Sold To :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Agent & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Vessel :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Vessel & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Lay Can\Lay Day :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Laycan & "</font></td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Berth :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Berth & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Commend :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Start & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Completed :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & _Stop & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Departed :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Depart & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        Return HTML
    End Function

    Private Function SendMail(ByVal Booking As String, ByVal SEND As String, ByVal Body As String) As Boolean
        Dim role As String = ""
        If (SEND = "PTO") Then
            role = clsGet.Get_EmailForSend("'00004','00012','00013','00014'") & ";" & clsGet.Get_EmailForSendAgent(Booking)
        ElseIf (SEND = "MARKETING") Then
            role = clsGet.Get_EmailForSend("'00003','00004','00012','00013','00014'") & ";" & clsGet.Get_EmailForSendAgent(Booking)
        End If
        Dim test As String = clsFc.sendmail(role, "", "iPORT", Body, "")
        If (test <> "") Then
            Return True
        Else
            Return False
        End If
    End Function

    Protected Sub btnGetTruckScale_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        'Dim txtTruckScale As TextBox = CType(gridProduct.FindControl("txtTruckScale"), TextBox)
        'txtTruckScale.Text = "xxx"
        Dim booking_no As String = ViewState("EditBooking").ToString()
        Dim indexEdit As String = ViewState("indexEdit").ToString()
        Dim db As New DB_Class()
        For Each gridRow As GridViewRow In gridProduct.Rows
            Dim txtTruckScale As TextBox = CType(gridRow.FindControl("txtTruckScale"), TextBox)
            Dim testLabel As Label = CType(gridRow.FindControl("testLabel"), Label)

            Dim dateFromTxt As TextBox = CType(gridRow.FindControl("txtTruckDateFrom"), TextBox)
            Dim timeFromTxt As TextBox = CType(gridRow.FindControl("txtTruckTimeFrom"), TextBox)
            Dim dateToTxt As TextBox = CType(gridRow.FindControl("txtTruckDateTo"), TextBox)
            Dim timeToTxt As TextBox = CType(gridRow.FindControl("txtTruckTimeTo"), TextBox)

            If (dateFromTxt.Text = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('กรุณาระบุวันที่ เริ่มต้น');", True)
                Exit Sub
            End If

            If (timeFromTxt.Text = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('กรุณาระบุเวลา เริ่มต้น');", True)
                Exit Sub
            Else
                Dim t As Date
                If (Not Date.TryParseExact(timeFromTxt.Text, "HH:mm", New CultureInfo("en-US"), DateTimeStyles.None, t)) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('ระบุเวลาเริ่มต้น ไม่ถูกต้อง');", True)
                    Exit Sub
                End If
            End If

            If (dateToTxt.Text = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('กรุณาระบุวันที่ สิ้นสุด');", True)
                Exit Sub
           
            End If

            If (timeToTxt.Text = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('กรุณาระบุเวลา สิ้นสุด');", True)
                Exit Sub
            Else
                Dim t As Date
                If (Not Date.TryParseExact(timeToTxt.Text, "HH:mm", New CultureInfo("en-US"), DateTimeStyles.None, t)) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('ระบุเวลาสิ้นสุด ไม่ถูกต้อง');", True)
                    Exit Sub
                End If
            End If

            Dim proName As String = gridProduct.DataKeys(gridRow.RowIndex)("Product_name").ToString()

            Dim transferGrid As GridView = CType(gridRow.FindControl("gridTransfer"), GridView)
            db.queryString = "select "
            db.queryString += "CAST(MAX(TruckScaleID) as nvarchar(10)) as maxId ,"
            db.queryString += "CAST(MIN(TruckScaleID) as nvarchar(10)) as minId ,"
            db.queryString += "CAST(SUM(Product_Weight) as nvarchar(10)) as productWeight,"
            db.queryString += "CAST(COUNT(TruckTypeID) as nvarchar(10)) as countTruck"
            db.queryString += " from v_TruckScale_Join_TruckType"

            Dim whereString As String
            whereString = " where Booking_no='" & booking_no & "' and Product='" & proName & "'"
            whereString += String.Format(" and DATEDIFF(MINUTE, CONVERT(datetime,'{0}',103),CONVERT(datetime,Date_Scale_IN+' '+Time_Scale_IN,103)) >= 0", dateFromTxt.Text + " " + timeFromTxt.Text)
            whereString += String.Format(" and DATEDIFF(MINUTE, CONVERT(datetime,Date_Scale_OUT+' '+Time_Scale_OUT,103),CONVERT(datetime,'{0}',103)) >=0", dateToTxt.Text + " " + timeToTxt.Text)

            db.queryString += whereString

            Dim btnTmp As Button = sender
            Dim rowGridItem As GridViewRow = CType(btnTmp.NamingContainer, GridViewRow)
            Dim curGridProRow As String = rowGridItem.RowIndex.ToString()

            Dim dtTruckScale As DataTable = db.getTable("truckScale")
            Dim newData As New DataTable()
            If (ViewState("TruckScale") IsNot Nothing) Then
                If (dtTruckScale.Rows(0)("minId").ToString() <> "") Then
                    newData = CType(ViewState("TruckScale"), DataTable)
                    newData.Merge(dtTruckScale)
                    ViewState("TruckScale") = newData
                End If
            Else
                If (dtTruckScale.Rows(0)("minId").ToString() <> "") Then
                    newData = dtTruckScale
                    ViewState("TruckScale") = newData
                End If
            End If

            If (newData.Rows.Count > 0) Then
                transferGrid.DataSource = newData
                transferGrid.DataBind()
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('ไม่พบรถบรรทุกในช่วงเวลาที่กำหนด');", True)
                Exit Sub
            End If

            Session("TruckScale" & curGridProRow) = newData

            txtTruckScale.Text = productWeightTotal.ToString("N", numberFormat).Replace(",", "")

            db.queryString = "select CAST(COUNT(ctType) as nvarchar(10)) as cntType,TruckType from v_Count_Truck"
            db.queryString += whereString
            db.queryString += " group by TruckType"
            Dim dtTruckType As DataTable = db.getTable("truckType")
            Dim newCountTruck As New DataTable()
            Dim sessName As String = "truckTypeGroup" & curGridProRow & transferGrid.Rows.Count - 1
            Session(sessName) = dtTruckType


            If (ViewState("countTruckType") IsNot Nothing And dtTruckType.Rows.Count > 0) Then
                newCountTruck = CType(ViewState("countTruckType"), DataTable)
                newCountTruck.Merge(dtTruckType)
            Else
                newCountTruck = dtTruckType
            End If

            ViewState("countTruckType") = newCountTruck



            
            Session("truckTypeGroup" & curGridProRow) = newCountTruck
            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('" & curGridProRow & "');", True)


            ' LINQ Expression ใช้สำหรับ count Truck Type โดย Gruup By TruckType
            Dim dtEnum As IEnumerable(Of DataRow) = newCountTruck.AsEnumerable()
            Dim disT = From t In dtEnum Where t.Item("TruckType").ToString() <> "" _
                   Group t By Key = t.Item("TruckType") Into Group Select TruckType = Key, TotalCount = Group.Sum(Function(p) p("cntType"))

            disT = From t In disT Where t.TotalCount > 0 Select t

            Dim reptTruck As Repeater = CType(gridRow.FindControl("reptTruckCount"), Repeater)
            If (disT IsNot Nothing) Then
                reptTruck.DataSource = disT
                reptTruck.DataBind()
            End If
            
            'Dim drc As DataRowCollection = db.getTableWhere("v_Sum_Weight_Truck_Scale", "Booking_no='" & booking_no & "' and Product='" & proName & "'")
            ''testLabel.Text = db.queryString
            'If (drc.Count > 0) Then
            '    txtTruckScale.Text = drc(0)("SumProWeight").ToString()
            'End If

            'db.queryString = "select * from v_Count_Truck where Booking_no = '" & booking_no & "' and Product='" & proName & "'"
            'Dim dtTruckTypeCount As DataTable = db.getTable("countTruck")
            'Dim reptTruck As Repeater = CType(gridRow.FindControl("reptTruckCount"), Repeater)
            'reptTruck.DataSource = dtTruckTypeCount
            'reptTruck.DataBind()

        Next

    End Sub
    Public Sub reptTruckCount_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim item As RepeaterItem = e.Item
        If (item.ItemType = ListItemType.Item Or item.ItemType = ListItemType.AlternatingItem) Then
            Dim sumHide As HiddenField = CType(item.FindControl("sumTruckHide"), HiddenField)
            Dim sumTruck As Integer = CInt(sumHide.Value)
            sumTotalTruck += sumTruck
            
            'Dim truckId As HiddenField = CType(item.FindControl("hideTruckId"), HiddenField)
            'Dim lb As Label = CType(item.FindControl("labelTruckCount"), Label)
            'lb.Text = truckId.Value
        ElseIf (item.ItemType = ListItemType.Footer) Then
            Dim sumTotalLb As Label = CType(item.FindControl("sumTotalTruckLabel"), Label)
            sumTotalLb.Text = sumTotalTruck.ToString()
        End If
    End Sub
End Class